views:

33

answers:

1

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 lockTable.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

+1  A: 

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.

Ben Robinson
But it'd allow me to use it for multiple tables at design time, correct?
Refracted Paladin
stupid question but what is an example of what I'd put for `TEntity`?
Refracted Paladin
hmm, thinking about it you would probably have to design an interface and apply it to all your tables, hanf on i'll update the answer
Ben Robinson
I have updated my answer.
Ben Robinson