John
John

Reputation:

Obtaining a table by the item type in LINQ to SQL

How can you make something like this generic

return from items in _db.Table
    select items;

I would like to do something like this

public class Data<T> ( where T is the model object )

so the Table will change to the value of T

How would this look as a generic class with a save method for instance

Thanks

Upvotes: 0

Views: 350

Answers (3)

jrummell
jrummell

Reputation: 43117

Adding to Marc Gravell's answer, you could have a generic update method that looks like this:

public void Update(TEntity entity, TEntity original)
{
    using (DataContext context = CreateContext())
    {
        Table<TEntity> table = context.GetTable<TEntity>();

        table.Attach(entity, original);
        context.SubmitChanges();
    }
}

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1064184

In LINQ-to-SQL, the data-context has GetTable<T>():

var table = _db.GetTable<T>();
etc

Upvotes: 4

leppie
leppie

Reputation: 117350

... _db.GetTable<MyType> ...

Upvotes: 0

Related Questions