[英]Entity Framework Linq query not generating where clause in SQL Server when passed as a predicate
I've created a brand new Project in .NET Core 3.1 and a query I am creating is generating a SQL query (viewed in SQL Server Profiler) that does not contain a where clause and instead reads in the entire table.我在 .NET Core 3.1 中创建了一个全新的项目,我正在创建的查询正在生成 SQL 查询(在 SQL 中查看) Is there a way to pass in a predicate and have that incorporated into the SQL statement that is ultimately generated?
有没有办法传入一个谓词并将其合并到最终生成的 SQL 语句中?
In the below function query1
is an IQueryable<Balance>
and query2
is an IEnumerable<Balance>
:在下面的 function
query1
是IQueryable<Balance>
和query2
是IEnumerable<Balance>
:
public int GetCount(Func<Balance, bool> predicate)
{
var query1 = (from b in _appContext.Balance
select b
);
var query2 = query1.Where(predicate);
var count = query2.Count();
return count;
}
Called like this:像这样调用:
GetCount(p => p.Email == 'test@gmail.com');
This answer helped me out: Create Expression from Func .这个答案帮助了我: 从 Func 创建表达式。
Basically I had to wrap the Func in an Expression as follows:基本上我必须将 Func 包装在一个表达式中,如下所示:
public int GetCount(Expression<Func<Balance, bool>> predicate)
{
return = (from b in _appContext.TableName
select b
).Where(predicate).Count();
}
The same call worked:同样的电话有效:
GetCount(p => p.Email == 'test@gmail.com');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.