C# EF Context.Set<;T>;()方法

C# EF Context.Set<;T>;()方法,c#,entity-framework,C#,Entity Framework,我想获得一个条件为lambda表达式的数据,如中所示 public IEnumerable<T> GetBy(Func<T, bool> condition) { var test = Context.Set<StateInfo>().Where(p => p.CustomerID != null && p.CustomerID == 5); var test2= Context.Set<T

我想获得一个条件为lambda表达式的数据,如中所示

public IEnumerable<T> GetBy(Func<T, bool> condition)
    {
        var test = Context.Set<StateInfo>().Where(p => p.CustomerID != null && p.CustomerID == 5);

        var test2= Context.Set<T>().Where(condition);
               .
               .
    }
public IEnumerable GetBy(Func条件)
{
var test=Context.Set(),其中(p=>p.CustomerID!=null&&p.CustomerID==5);
var test2=Context.Set().Where(条件);
.
.
}

当我查看测试对象SQL查询时,它会在其中使用where子句。但test2对象查询类似于仅从表中选择*。它从数据库获取所有数据,然后在代码端使用when方法。我如何使用where子句获取数据,因为test2查询处理大数据需要很长时间。唯一的区别是其中一个代码具有泛型类,但sql查询不同。谢谢。

改用
表达式

Expression<Func<T, bool>> condition
表达式条件
使用
Func
时,不能将其转换为SQL。你得到整个数据,然后在内存中过滤它们。
如果是
表达式
,它将被转换为SQL,您将从SQL server获得过滤后的数据。

您的条件类型为
Func
。当您查看
context.Set().Where()
的重载时,您可以看到,接受
Func
的重载返回
IEnumerable
instaead of
IQuerable
,因为它从源代码获取所有数据,然后应用过滤器。您应该使用
表达式条件
。您的方法应该类似于:

public IQueryable<T> GetBy<T>(Expression<Func<T, bool>> condition)
    where T : class
{
    return Context.Set<T>().Where(condition);               
}
public IQueryable GetBy(表达式条件)
T:在哪里上课
{
返回Context.Set().Where(条件);
}
注意:如果要在过滤后返回IEnumerable,可以将其保留为:

public IEnumerable<T> GetBy<T>(Expression<Func<T, bool>> condition)
    where T : class
{
    // Should also work without AsEnumerable()
    return Context.Set<T>().Where(condition).AsEnumerable();               
}
public IEnumerable GetBy(表达式条件)
T:在哪里上课
{
//也应该在没有AsEnumerable()的情况下工作
返回Context.Set().Where(condition).AsEnumerable();
}

Idk,但我以前试过,比如
Context.Set().AsQueryable().Where(condition)
。如果没有AsQueryable(),它现在可以工作了。非常感谢@Brucay,无需在
Set()
上使用
AsQueryable()
当您使用
Func
谓词调用
Where(condition)
时,此重载方法在内部将所有数据作为可枚举数据获取,然后应用过滤器。
Context.Set().Where(condition).AsEnumerable()我这样更改了代码,但它给出了错误:非公共成员=错误CS1503:参数1:无法从“System.Collections.Generic.IEnumerable”转换为“System.Collections.Generic.IEnumerable”@Burcay,如何调用该方法?
resultCandidate=\u repo.GetBy(p=>resultStateInfo.Select(s=>s.MemberID)。包含(p.CandidateMemberID)).ToList();
Idk,但我以前尝试过它,比如
Context.Set().AsQueryable().Where(condition)
。如果没有AsQueryable(),现在就可以了。非常感谢!