简体   繁体   English

所有表的LINQ 2 SQL方法

[英]LINQ 2 SQL Method for all tables

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. 我有一个L2S方法,适用于我想编写一次的每个表。 This is to set a soft lock column where I will also need a Read and UnLock method. 这是为了设置一个软锁列,在此我还需要一个ReadUnLock方法。 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 lockTable.PlanID == TablePrimaryKey
                               select lockTable).Single();

            tableToLock.Locked = true;
            context.SubmitChanges();
        }
    }

What I would like to do is replace context.tblPlans with context.TableName . 我想做的是用context.tblPlans替换context.TableName Is this possible in LINQ? 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 您还必须使用以下事实:将Linw2SQL表创建为部分类以对其进行扩展,以便所有relevent表都实现IPlanTable

You would use it like below: 您可以像下面这样使用它:

LockRow<tblPlan>(23); 

simply replace tblPlan with whatever the name of your table class is. 只需将tblPlan替换为表类的名称即可。

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. 但是,这不允许您在运行时设置表,LinqToSQL是面向对象的,并且类型安全,指定要检索的表与其设计工作方式相反。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM