c# – linq对实体无法识别方法

前端之家收集整理的这篇文章主要介绍了c# – linq对实体无法识别方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这些方法
  1. public int count(
  2. Guid companyId,Expression<Func<T,bool>> isMatch)
  3. {
  4. var filters = new Expression<Func<T,bool>>[]{
  5. x => x.PriceDefinition.CompanyId == companyId,isMatch
  6. };
  7.  
  8. return GetCount(filters);
  9. }
  10.  
  11. public virtual int GetCount(
  12. IEnumerable<Expression<Func<T,bool>>> filters)
  13. {
  14. IQueryable<T> _query = ObjectSet;
  15.  
  16. if (filters != null)
  17. {
  18. foreach (var filter in filters)
  19. {
  20. _query = _query.Where(filter);
  21. }
  22. }
  23.  
  24. return _query.Count();
  25. }

使用时:

  1. count(some_guid,x => x.IsMatch(entityId,inviterId,routeId,luggageTypeId));

我得到以下例外:

  1. 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])' method,and this method cannot be translated into a store expression.

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

解决方法

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

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

  1. SELECT COUNT(*)
  2. FROM ...
  3. LEFT JOIN ...
  4. WHERE IsMatch(....)

因为EF验证传递给查询函数名称,它会抛出异常,因为它不了解sql Server上的IsMatch等效项.

在Linq-to-entities中可以使用的唯一可能的功能是:

> Cannonical functions,具有预定义映射到sql等价物
> EdmFunctions

EdmFunctions是用EdmFunctionAttribute标记方法,它将.NET函数映射到sql对应物.那些函数通常不能在普通的.NET代码中执行,因为它们什么都不做,也不会抛出异常.他们只是Linq对实体的功能占位符.可用的EdmFunction是:

> System.Data.Objects.EntityFunctions中的预定义EdmFunctions
> System.Data.Objects.sqlClient.sqlFunctions中的sql Server的预定义EdmFunctions(非紧凑型)
>自定义映射sql函数 – Entity设计器中的导入向导允许您导入sql函数(表值函数除外).之后可以编写自定义静态.NET函数,并将其通过EdmFunction属性映射到导入设计器的sql函数.
>自定义模型定义的函数 – 这是在EDMX文件中手动编写的特殊功能(以XML格式打开).它是Entity sql自定义可重用部分.

我已经在另一个答案中描述了how to create model defined function.创建映射SQL function is pretty similar.而不是在EDMX中手动创建Function元素,您将将EdmFunctionAttribute属性映射到导入的sql函数.

猜你在找的C#相关文章