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

时间:2010-10-02 17:09:05

标签: c# entity-framework linq-to-entities repository-pattern

我看到这段代码与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是一个扩展IQueryable功能的List。

有人可以解释为什么会出现这种错误吗?

1 个答案:

答案 0 :(得分:109)

<强>原因: 按照设计, 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, what is not supported? 了解详情。 另请查看 LINQ to Entities, Workarounds on what is not supported 以获取有关可能解决方案的详细讨论。 (两个链接都是缓存版本,因为原始网站已关闭)