Wednesday, April 13, 2011

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

From stackoverflow
  • ... _db.GetTable<MyType> ...
    
  • In LINQ-to-SQL, the data-context has GetTable<T>():

    var table = _db.GetTable<T>();
    etc
    
    Marc Gravell : Did you mean this for leppie? I had brackets in my post... try adding them...
  • 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();
        }
    }
    

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.