LINQ to Entities无法识别Let语句的方法

时间:2013-08-27 16:22:14

标签: entity-framework linq-to-entities entity-framework-5

我正在将使用LINQ to SQL的应用程序转换为LINQ to Entities。我使用了一个存储库模式,我运行的问题在LINQ to SQL中有效但不是实体。

在我的数据层中,我使用LINQ语句填充我的对象图,这样我的数据库实体就不会在其他任何地方公开。在这个例子中,我有一个Lookup Respository,它返回一个Categories列表。它看起来像这样:

public IQueryable<Entities.DomainModels.Category> getCategories()
    {
        return (from c in Categories
                where !c.inactive
                orderby c.categoryName
                select new Entities.DomainModels.Category
                {
                    id = c.categoryID,
                    category = c.categoryName,
                    inactive = c.inactive
                });
    }

稍后,我想将类别放入子查询中,它看起来像这样:

var d = from p in Programs
    let categories = (from pc in p.Categories
                      join c in getCategories() on pc.categoryID equals c.id
                      select c)
   select new 
    {
        id = p.id,
        title = p.title
       categories = categories.ToList()
        };

当我运行它时,我收到以下错误:

  

LINQ to Entities无法识别方法'System.Linq.IQueryable`1 [Entities.DomainModels.Category] ​​getCategories()'方法,并且此方法无法转换为商店表达式。

作为参考,以下工作虽然它不返回我需要的数据(它基本上是一个连接):

var q = from p in Programs
    from pc in p.Categories
    join c in getCategories() on pc.categoryID equals c.id
    select new 
    {
        id = p.id,
            category = c
        };

我理解错误在概念中意味着什么,但是LINQ to SQL会使它工作。我在整个数据层都有这种模式,我真的想保留它。这应该有用吗?如果没有,我怎么能修改它而不混合我的图层。

1 个答案:

答案 0 :(得分:1)

你无法将getCategories()传递给EF。

查询必须可以破坏表达式树。

首先计算getCategories()。

例如

var simpleList = getCategories().Select(id).Tolist;

然后使用contains

where(t=> simpleList.Contains(t.CatId)   // or the query syntax equivalent