方法无法转换为商店表达式


89

我看到此代码可用于LINQ to SQL,但是当我使用Entity Framework时,它将引发以下错误:

LINQ to Entities无法识别方法'System.Linq.IQueryable'1 [MyProject.Models.CommunityFeatures] GetCommunityFeatures()'方法,并且该方法无法转换为商店表达式。

存储库代码是这样的:

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是一个List,它扩展了IQueryable的功能。

有人可以解释为什么会发生此错误吗?

Answers:


115

原因: 根据设计,LINQ to Entities要求将整个LINQ查询表达式转换为服务器查询。在翻译查询之前,只会在客户端上评估一些不相关的子表达式(不依赖于服务器结果的查询中的表达式)。不支持没有已知转换的任意方法调用,例如本例中的GetHomeFeatures()。
更具体地说,LINQ to Entities仅支持无参数构造函数Initializers

解决方案: 因此,要克服此异常,您需要将子查询合并到GetCommunityFeatures()GetHomeFeatures()的主查询中而不是直接从LINQ查询中调用方法。另外,您尝试使用其参数化构造函数实例化LazyList的新实例时也遇到了问题,就像您可能在LINQ to SQL中所做的那样。为此,解决方案是切换到LINQ查询的客户端评估(LINQ to Objects)。这将要求您在调用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,关于不支持的解决方法,以详细讨论可能的解决方案。(这两个链接都是缓存的版本,因为原始网站已关闭)

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.