实体框架,动态请求实体

时间:2013-04-12 15:55:35

标签: .net database linq entity-framework mapping

我有一个用EF 5.0.0映射的数据库

我在某些列表中显示数据。我的数据以“经典方式”检索:

using (myContext db = new myContext())
{

    var products = db.products.Select(p => p).ToList();
}

我必须像我拥有的​​那样做,

有没有办法动态地制作它? :

using (myContext db = new myContext())
{
    type currentType = myTable1Type
    var currentList = db.currentType.Select(p => p).ToList();
}

3 个答案:

答案 0 :(得分:2)

尝试使用DbContext.Set Method (Type)

using (myContext db = new myContext())
{
    type currentType = myTable1Type
    var currentList = db.Set(currentType).Select(p => p).ToList();
}

答案 1 :(得分:0)

查看Context.Set()方法组。

答案 2 :(得分:0)

这种方法对我有用:

IDbSet GetDbSet(Type currentType, Context db)
{
    dynamic instance = Activator.CreateInstance(currentType);
    return GetDbSetFromInstance(instance, db);
}

IDbSet GetDbSetFromInstance<T>(T instance, Context db)
    where T : class
{
    var set = db.Set<T>();
    if (set == null)
    {
        throw new Exception();
    }
    return set;
}