方法不能转换成商店expression式
我看到这个代码与LINQ to SQL的工作,但是当我使用entity framework,它会引发这个错误:
LINQ to Entities不能识别方法'System.Linq.IQueryable'1 [MyProject.Models.CommunityFeatures] GetCommunityFeatures()'方法,并且此方法不能被转换成存储expression式。
存储库代码是这样的:
public IQueryable<Models.Estate> GetEstates() { return from e in entity.Estates let AllCommFeat = GetCommunityFeatures() let AllHomeFeat = GetHomeFeatures() select new Models.Estate { EstateId = e.EstateId, AllHomeFeatures = new LazyList<HomeFeatures>(AllHomeFeat), AllCommunityFeatures = new LazyList<CommunityFeatures>(AllCommFeat) }; } public IQueryable<Models.CommunityFeatures> GetCommunityFeatures() { return from f in entity.CommunityFeatures select new CommunityFeatures { Name = f.CommunityFeature1, CommunityFeatureId = f.CommunityFeatureId }; } public IQueryable<Models.HomeFeatures> GetHomeFeatures() { return from f in entity.HomeFeatures select new HomeFeatures() { Name = f.HomeFeature1, HomeFeatureId = f.HomeFeatureId }; }
LazyList是一个扩展了IQueryablefunction的List。
有人可以解释为什么这个错误发生?
原因:通过devise, LINQ to Entities要求将整个LINQ查询expression式转换为服务器查询。 在查询翻译之前,只有less数不相关的子expression式(查询中的expression式不依赖于服务器的结果)在客户端上进行评估。 在这种情况下,不具有已知翻译的任意方法调用(如GetHomeFeatures())不受支持。
更具体地说,LINQ to Entities只支持无参数构造函数和初始化方法 。
解决scheme:因此,为了克服这个exception,您需要将您的子查询合并到GetCommunityFeatures()和GetHomeFeatures()的主查询中,而不是直接从LINQ查询中调用方法。 此外,还有一个问题就是您尝试使用其参数化构造函数实例化LazyList的新实例,就像您在LINQ to SQL中所做的一样。 为此,解决scheme将切换到客户端评估的LINQ查询(LINQ到对象)。 这将需要您在调用LazyList构造函数之前调用您的LINQ to Entities查询的AsEnumerable方法。
像这样的东西应该工作:
public IQueryable<Models.Estate> GetEstates() { return from e in entity.Estates.AsEnumerable() let AllCommFeat = from f in entity.CommunityFeatures select new CommunityFeatures { Name = f.CommunityFeature1, CommunityFeatureId = f.CommunityFeatureId }, let AllHomeFeat = from f in entity.HomeFeatures select new HomeFeatures() { Name = f.HomeFeature1, HomeFeatureId = f.HomeFeatureId }, select new Models.Estate { EstateId = e.EstateId, AllHomeFeatures = new LazyList<HomeFeatures>(AllHomeFeat), AllCommunityFeatures = new LazyList<CommunityFeatures>(AllCommFeat) }; }
更多信息:请看看LINQ to Entities,什么是不支持的? 获取更多信息。 另外请查看LINQ to Entities,有关可能解决scheme的详细讨论不支持的解决方法。 (这两个链接是caching版本,因为原来的网站是closures的)