[英]Entity Framework apply filter with entities that have lists
I have this code using Entity Framework 我有使用实体框架的这段代码
var test = _dbContext.Category
.Include(t => t.Items)
.Where(t => t.items.show == true)
.ToList();
A category has a list of items. 类别具有项目列表。 However, I can not apply the filter
show == true
. 但是,我无法应用过滤器
show == true
。
Why is it happening? 为什么会这样呢? How do I fix it?
我如何解决它?
Thanks 谢谢
The items in t=>t.items.show==true
is a collection not the individual item, so there is no show
property. t=>t.items.show==true
中的项目是一个集合,而不是单个项目,因此没有show
属性。
If you need to load only the items with show==true you can load them separately: 如果只需要使用show == true加载项目,则可以分别加载它们:
var categories = _dbContext.Category.ToList();
var items = _dbContext.Category.SelectMany(x => x.Items).Where(x => x.show == true).ToList();
EF will attach the items to appropriate categories automatically. EF会将这些项目自动添加到适当的类别。
You can use Any
for this kind of request and you may avoid Include if you won't use items apart from filtering. 您可以将
Any
用于此类请求,并且如果不使用除过滤之外的其他项目,则可以避免使用Include。
var test = _dbContext.Category
.Where(t => t.items.Any(item=> item.show == true))
.ToList();
PS: I strongly recommend to use C# naming convention. PS:我强烈建议使用C#命名约定。
Items
and Show
are more accurate if they are properties. Items
和Show
是属性,则它们将更加准确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.