繁体   English   中英

Lambda表达式过滤使用Entity Framework包括相关数据

[英]Lambda expression filtering included related data with Entity Framework

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

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

错误:

包含路径表达式必须引用在类型上定义的导航属性。 使用虚线路径作为参考导航属性,使用“选择”运算符作为集合导航属性。

更新

 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();

但是现在我需要将AnonymousType强制转换为Category

如果需要,您的查询没有任何意义:

类别中的可见产品

如果您确实想要可见的产品,请尝试以下操作:

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

注意:未经测试

也许像这样:

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;

也没有测试...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM