简体   繁体   English

创建一个数据库集<T>在实体框架中动态?

[英]Create a DbSet<T> dynamically in Entity Framework?

In LINQ to SQL, I can create a repository dynamically using DataContext.GetTable<T> .在 LINQ to SQL 中,我可以使用DataContext.GetTable<T>动态创建存储库。 Is there a similar way to do this in Entity Framework 4 other than declaring the properties on the specific DbContext ?除了在特定DbContext上声明属性之外,在 Entity Framework 4 中是否有类似的方法来执行此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:我想知道如何像使用 LINQ to SQL 那样动态创建/获取对MySets的引用, MySets

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

DbContext有这个方法:

  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.不要担心第二次加载和复制 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.我用它来为不经常更改其内容的基本表执行缓存功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM