My Title may be slightly off but here is what I am trying to do. I have a L2S Method that would be for every table that I would like to write once. This is to set a soft lock column where I will also need a Read
and UnLock
method. Here is what I have so far:
public static void LockRow(string TableName, int TablePrimaryKey)
{
using (var context = McpDataContext.Create())
{
var tableToLock = (from lockTable in context.tblPlans
where lock开发者_开发问答Table.PlanID == TablePrimaryKey
select lockTable).Single();
tableToLock.Locked = true;
context.SubmitChanges();
}
}
What I would like to do is replace context.tblPlans
with context.TableName
. Is this possible in LINQ? How so? I am assumming that I am going about it the wrong way so I'd be grateful for some direction/pointers.
Thanks
Update becuase the first example would not work.
You could do it with a generic method and an interface:
public interface IPlanTable
{
int PlanID { get; set; }
}
public static void LockRow<TEntity>(int TablePrimaryKey) where TEntity : class, IPlanTable
{
using (var context = McpDataContext.Create())
{
var tableToLock = (from lockTable in context.GetTable<TEntity>()
where lockTable.PlanID == TablePrimaryKey
select lockTable).Single();
tableToLock.Locked = true;
context.SubmitChanges();
}
}
You will also have to use the fact that the Linw2SQL tables are created as partial classes to extend them so all the relevent table implement IPlanTable
You would use it like below:
LockRow<tblPlan>(23);
simply replace tblPlan
with whatever the name of your table class is.
However this won't allow you to set the table at runtime, LinqToSQL is object orientated and type safe, specifying the table you want to retreive is contrary to how it si designed to work.
精彩评论