【问题标题】:EF Core stored where Func does not generate SQL where clauseEF Core 存储 where Func 不生成 SQL where 子句
【发布时间】:2020-01-03 01:24:22
【问题描述】:

我正在尝试创建一个 EF 通用存储库,但是当将具有 Func where 的变量作为参数传递给方法时,不会生成 where 子句。

例子:

这会生成 SQL where 子句

 var data = dbSet.Where((m => (m.Field != null && m.Field.Contains(searchValue))));

这不是:

var whereClause = (m => (m.Field != null && m.Field.Contains(searchValue)));
var data = dbSet.Where(whereClause);

【问题讨论】:

  • var whereClause = ... 无法编译。无论如何,请确保使用Expression<Func<...>> 参数,例如Queryable 方法,而不是匹配Enumerable 方法的Func<…>,因此不会被转换为SQL 并将在内存中执行。

标签: c# .net asp.net-core entity-framework-core


【解决方案1】:

正如@Ivan Stoev 告诉我们的,这不能编译:var whereClause = ...

但你可以这样做:

var data = FindEntity((m => (m.Field != null && m.Field.Contains(searchValue))));
//T is your dbSet Data type
private IEnumerable<T> FindEntity(Expression<Func<T, bool>> whereClause)
{
    return dbset.Where(whereClause)
        .AsEnumerable();
}

【讨论】:

  • 谢谢你,它有效,我曾经使用 Func 而不是 Expression
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-22
  • 2012-10-14
  • 1970-01-01
  • 2014-01-24
  • 1970-01-01
  • 2012-06-08
  • 2021-06-15
相关资源
最近更新 更多