c# – linq对实体无法识别方法
我有这些方法:
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(); } 使用时: count(some_guid,x => x.IsMatch(entityId,inviterId,routeId,luggageTypeId)); 我得到以下例外: 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,您的代码意味着如下: SELECT COUNT(*) FROM ... LEFT JOIN ... WHERE IsMatch(....) 因为EF验证传递给查询的函数名称,它会抛出异常,因为它不了解SQL Server上的IsMatch等效项. 在Linq-to-entities中可以使用的唯一可能的功能是: > Cannonical functions,具有预定义映射到SQL等价物 EdmFunctions是用EdmFunctionAttribute标记的方法,它将.NET函数映射到SQL对应物.那些函数通常不能在普通的.NET代码中执行,因为它们什么都不做,也不会抛出异常.他们只是Linq对实体的功能占位符.可用的EdmFunction是: > System.Data.Objects.EntityFunctions中的预定义EdmFunctions 我已经在另一个答案中描述了how to create model defined function.创建映射SQL function is pretty similar.而不是在EDMX中手动创建Function元素,您将将EdmFunctionAttribute属性映射到导入的SQL函数. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |