linq to entities无法识别方法

Nao*_*aor 10 .net c# linq-to-entities entity-framework

我有这些方法:

   public int count(
        Guid companyId, Expression<Func<T, bool>> isMatch)
    {
        var filters = new Expression<Func<T, bool>>[]{
            x => x.PriceDefinition.CompanyId == companyId,
            isMatch
        };

        return GetCount(filters);
    }

public virtual int GetCount(
            IEnumerable<Expression<Func<T, bool>>> filters)
        {
            IQueryable<T> _query = ObjectSet;

            if (filters != null)
            {
                foreach (var filter in filters)
                {
                    _query = _query.Where(filter);
                }
            }

           return _query.Count();
        }
Run Code Online (Sandbox Code Playgroud)

使用时:

count(some_guid, x => x.IsMatch(entityId, inviterId, routeId, luggageTypeId));
Run Code Online (Sandbox Code Playgroud)

我得到以下异常:

LINQ to Entities does not recognize the method 'Boolean IsMatch(System.Nullable`1[System.Int64], System.Nullable`1[System.Int64], System.Nullable`1[System.Int64], System.Nullable`1[System.Int64])' method, and this method cannot be translated into a store expression.
Run Code Online (Sandbox Code Playgroud)

这是什么原因?
我该如何解决?

Lad*_*nka 14

使用linq-to-entities时,不能在查询中使用任意.NET方法.查询中使用的每个方法都必须可以转换为SQL.它无法帮助您返回,Expession<Func<entityType, bool>>因为必须为数据库服务器上的每条记录评估条件.

对于EF,您的代码意味着:

SELECT COUNT(*)
FROM ...
LEFT JOIN ...
WHERE IsMatch(....) 
Run Code Online (Sandbox Code Playgroud)

因为EF验证传递给查询的函数名称,所以它将抛出异常,因为它不知道SQL服务器上的IsMatch等价物.

可以在Linq到实体中使用的唯一可能的功能是:

EdmFunctions是标记有EdmFunctionAttribute.NET函数到SQL对应的映射的方法.这些函数通常不能在常见的.NET代码中执行,因为它们什么都不做或抛出异常.它们只是Linq-to-entities的功能占位符.可用的EdmFunction是:

  • 预定义的EdmFunctions System.Data.Objects.EntityFunctions
  • SQL Server中的预定义EdmFunction(非紧凑) System.Data.Objects.SqlClient.SqlFunctions
  • 自定义映射SQL函数 - 实体设计器中的导入向导允许您导入SQL函数(表值函数除外).您可以在此之后编写自定义静态.NET函数并将其按EdmFunction属性映射到导入到设计器的SQL函数.
  • 自定义模型定义的函数 - 这是在EDMX文件中手动编写的特殊函数(以XML格式打开).它是Entity SQL的自定义可重用部分.

我已经描述了如何在另一个答案中创建模型定义函数.创建映射的SQL函数非常相似.Function您可以将EdmFunctionAttribute属性映射到导入的SQL函数,而不是在EDMX 中手动创建元素.