如何用EF和C#编写通用查询

时间:2016-06-08 08:30:09

标签: c# entity-framework-6

我想在实体框架中编写一个查询,如下所示:

T entity = (from e in myContext.typeof(T) )

我尝试使用字符串concat,但这不适用于从myContext

获取成员

更多代码:

public T GetEntity<T>(Guid entityId, string connectionString)
{
    using (RContext rpContext = new RContext(connectionString))
    {

        var entity = (from e in rpContext.Set<T>()
                                    where e.Id == entityId
                                    select e).FirstOrDefault();
                    return (T) Convert.ChangeType(entity, typeof(T));

    }
}

1 个答案:

答案 0 :(得分:0)

您可以像这样访问通用Set方法:

var entities = (from e in myContext.Set<T>());

<强>更新 您需要在方法中添加泛型类型约束,以确保泛型类型T与已应用于方法DbContext.Set<T>的约束相匹配。

更新2: 你不需要施放你的实体;它已经是typeof(T)

public T GetEntity<T>(Guid entityId, string connectionString)
    where T : class
{
    using (RContext rpContext = new RContext(connectionString))
    {

        return (from e in rpContext.Set<T>()
                where e.Id == entityId
                select e).FirstOrDefault();
    }
}

更新3: 您可以将谓词直接传递到FirstOrDefault方法,假设您没有附加到linq语法。

public T GetEntity<T>(Guid entityId, string connectionString)
    where T : class
{
    using (RContext rpContext = new RContext(connectionString))
    {
        return rpContext.Set<T>().FirstOrDefault(e => e.Id == entityId);
    }
}

更新4: 当您在方法中使用Id属性时,您还需要将方法约束到具有该属性的类型 - 通过约束公共接口或公共基类。如果它是基类,则可以删除class约束。