c# - 在 Entity Framework 查询中使用 Func<>

标签 c# linq entity-framework

我有以下 Entity Framework 查询:

Func<Company, bool> filter;
if (officeId != 0)
    filter = company => !company.IsDeleted && company.OfficeCompanies.Any(c => c.OfficeId == officeId);
else
    filter = company => !company.IsDeleted;

var companies = from c in Repository.Query<Company>()
                where filter(c) &&
                    (relationshipTypes.Count() == 0 || relationshipTypes.Any(r => r == c.TypeEnumIndex)) &&
                    c.Description.Contains(term)
                orderby c.Description
                select new JqueryUiAutoCompleteItem
                {
                    label = c.Description,
                    value = SqlFunctions.StringConvert((double)c.Id)
                };

它给我错误:

The LINQ expression node type 'Invoke' is not supported in LINQ to Entities.

如果我删除查询主体中对 filter() 的引用,则不会出现错误。

我理解这个错误的意思:我正在使用无法转换成SQL的代码。但是我的 filter() 有什么不能转换成 SQL 的?

最佳答案

您需要将 Func 切换为 Expression,然后将该表达式直接传递给 LINQ fluent 语法中的 Where。我认为没有办法在查询语法中使用表达式。

Expression<Func<Company, bool>> filter; //<-- changed type
if (officeId != 0)
    filter = company => !company.IsDeleted && company.OfficeCompanies.Any(c => c.OfficeId == officeId);
else
    filter = company => !company.IsDeleted;

var companies = from c in Repository.Query<Company>().Where(filter) // <-- changed syntax
                where (relationshipTypes.Count() == 0 || relationshipTypes.Any(r => r == c.TypeEnumIndex)) &&
                    c.Description.Contains(term)
                orderby c.Description
                select new JqueryUiAutoCompleteItem
                {
                    label = c.Description,
                    value = SqlFunctions.StringConvert((double)c.Id)
                };

关于c# - 在 Entity Framework 查询中使用 Func<>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25672506/

相关文章:

c# - 为什么我无法通过 C# 应用程序连接到远程 SQL 服务器?

c# - 使用查询表达式时缓存?

c# - 任务完成后如何销毁谷歌驱动器 token ?

c# - 使用 Controller 名称和操作名称 main.js 时,asp.net core 的 Angular 2 设置问题

c# - Linq 用于不同计数

c# - LINQ to Entities 选择带有表达式参数的列

mysql - 实体中的许多 EntityCollections 在 RIA 服务中引发 "implement IConvertible"异常

entity-framework - Entity Framework : Modeling against an existing database scheme

c# - 通过 C# 代码更新 web.config

c# - 避免 DataTable 查询和构建中的重复