【问题标题】:Lambda expression filtering included related data with Entity FrameworkLambda 表达式过滤包括与实体框架相关的数据
【发布时间】:2012-07-05 06:37:56
【问题描述】:

我只需要过滤某个类别中的可见产品,但它不起作用。

Category category = db.Categories
            .Include(c => c.Products.Where(p => p.IsVisible))
            .First(c => c.CategoryID == id);

错误:

包含路径表达式必须引用在类型上定义的导航属性。对引用导航属性使用虚线路径,对集合导航属性使用 Select 运算符。

更新

 var result = (from c in db.Categories
                             where c.CategoryID == id
                             select new
                             {
                                 CategoryID = c.CategoryID,
                                 Description = c.Description,
                                 Products = (from p in db.Products
                                             where p.IsVisible
                                             && p.CategoryID == c.CategoryID
                                             orderby p.DateSent descending
                                             select p)
                             }).FirstOrDefault();

但现在我需要将匿名类型转换为类别

【问题讨论】:

标签: c# entity-framework lambda filtering


【解决方案1】:

可能是这样的:

var category = db.Products.Where(p=>p.IsVisible && p.CategoryID == id).Include("Category").ToList().Select( p=> p.Category).Distinct();

由于 ToList,它可能并不理想……但我现在看不到其他方法。

也许您可以将 Distinct 更改为 FirstOrDefault()...

var category = db.Products.Where(p=>p.IsVisible && p.CategoryID == id).Include("Category").ToList().FirstOrDefault().Category;

也没有测试...

【讨论】:

    【解决方案2】:

    如果您愿意,您的查询没有意义:

    某个类别的可见产品

    如果你真的想要可见的产品,试试这个:

    var visibleProducts = db.Categories
                            .Where(c => c.CategoryID == id)
                            .Select(c => c.Products.Where(p => p.IsVisible));
    

    注意:未经测试

    【讨论】:

    • 我会测试,但我需要类别数据和可见产品列表
    • 你已经有了类别的ID,你可以做2次查询。第一个查询获取类别,第二个查询从类别中获取可见产品。这样你就有了。
    • 我知道我可以使用 2 个查询,但由于性能原因,最好只使用 1 个。
    • 不会有性能问题,无论如何它已经必须执行这两个查询。不妨分别存储两者的结果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-14
    • 2014-10-09
    • 1970-01-01
    • 1970-01-01
    • 2013-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多