Create a DbSet<T> dynamically in Entity Framework?

*爱你&永不变心* 提交于 2019-12-18 12:09:51

问题


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: DbContext
{
    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>();

回答1:


DbContext has method for this:

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



回答2:


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.



来源:https://stackoverflow.com/questions/5308336/create-a-dbsett-dynamically-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!