方法无法转换为存储表达式。

25 浏览
0 Comments

方法无法转换为存储表达式。

我在使用LINQ to SQL时看到这段代码能够正常工作,但是当我使用Entity Framework时,会抛出以下错误:

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

这是仓储代码:

public IQueryable GetEstates()
{
    return from e in entity.Estates
           let AllCommFeat = GetCommunityFeatures()
           let AllHomeFeat = GetHomeFeatures()
           select new Models.Estate
                      {
                                EstateId = e.EstateId,
                                AllHomeFeatures = new LazyList(AllHomeFeat),
                                AllCommunityFeatures = new LazyList(AllCommFeat)
                      };
}
public IQueryable GetCommunityFeatures()
{
    return from f in entity.CommunityFeatures
           select new CommunityFeatures
                      {
                          Name = f.CommunityFeature1,
                          CommunityFeatureId = f.CommunityFeatureId
                      };
}
public IQueryable GetHomeFeatures()
{
    return from f in entity.HomeFeatures
           select new HomeFeatures()
           {
               Name = f.HomeFeature1,
               HomeFeatureId = f.HomeFeatureId
           };
}

LazyList是一个扩展IQueryable功能的列表。

有人能解释一下为什么会出现这个错误吗?

0
0 Comments

问题:(Method cannot be translated into a store expression)的原因是什么以及解决方法是什么?

原因:

按设计,LINQ to Entities要求整个LINQ查询表达式都要被翻译成服务器查询。只有一些不相关的子表达式(查询中不依赖于服务器结果的表达式)在查询被翻译之前在客户端进行评估。在这种情况下,像GetHomeFeatures()这样没有已知翻译的任意方法调用是不支持的。

更具体地说,LINQ to Entities只支持无参数的构造函数和初始化器。

解决方法:

因此,要解决这个异常,你需要将子查询合并到主查询中,而不是直接在LINQ查询中调用方法。此外,你试图使用带参数的构造函数实例化LazyList的代码行存在问题,就像你可能在LINQ to SQL中所做的那样。解决方法是切换到LINQ查询的客户端评估(LINQ to Objects)。这将要求在调用LazyList构造函数之前对LINQ to Entities查询调用AsEnumerable()方法。

像这样的代码应该可以工作:

public IQueryable 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(AllHomeFeat),
            AllCommunityFeatures = new LazyList(AllCommFeat)
       };
}

更多信息:请查看"LINQ to Entities, what is not supported?"以获取更多信息。

还可以查看"LINQ to Entities, Workarounds on what is not supported"以获取对可能解决方案的详细讨论。

(这两个链接是缓存版本,因为原始网站已经关闭)

0