开发者

Create a DbSet<T> dynamically in Entity Framework?

In LINQ to SQL, I can create a repository dynamically using DataContext.GetTable<T>. Is there a similar way to do this in Entity Framework 4 other than declaring the properties on the specific DbContext? For example:

public MyDbContext: DbCon开发者_StackOverflow中文版text
{
    public DbSet<MySet> MySets {get; set;}
}

I would like to know how can I create/get a reference to MySets dynamically as I can with LINQ to SQL as in:

var mySet = MyDbContext.GetTable<MySet>();


DbContext has method for this:

  var set = context.Set<MyEntity>();


Use:

DbSet<MyEntity> set = context.Set<MyEntity>();

Or, if you can't use the generic method:

DbSet set = context.Set(
    typeof( MyEntity )
);

Don't worry about second-loading and duplicating a POCO. Sets are cached internally by the Context.


This is my aproach:

    public static List<T> GetCollection<T>()
    {
        List<T> lstDynamic = null;

        using (MyDbContext db = new MyDbContext())
        {
            DbSet mySet = db.Set(typeof(T));
            mySet.Load();
            var list = mySet.Local.Cast<T>();

            lstDynamic = list.ToList();
        }
        return lstDynamic;
     }

And you call this function as:

List<Customer> lst = StaticClass.GetCollection<Customer>();

This returns your entire collection. I used this to perform a cache functionality for basic tables which don't change its content very often.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜