[英]How to use ICollection property to do a bool check
I have the following entities: 我有以下实体:
public class Order
{
public int Id { get; set; }
public ICollection<LineItem> LineItems { get; set; }
}
public class LineItem
{
public int Id { get; set; }
public int Qty { get; set; }
}
I would like to just check if an order has large items (qty > 50), so I would like to add a property to Order class like so: 我只想检查订单中是否有大件商品(数量> 50),所以我想向Order类添加一个属性,如下所示:
public class Order
{
public int Id { get; set; }
public ICollection<LineItem> LineItems { get; set; }
public bool HasLargeItems
{
get
{
return LineItems.Any(l => l.Qty > 50);
}
}
}
This however, doesn't work because of lazy-loading. 但是,由于延迟加载,此方法不起作用。 But if I use .Include(o => o.LineItems), it will fetch all the LineItems and then do an in-memory comparison.
但是,如果我使用.Include(o => o.LineItems),它将获取所有LineItem,然后进行内存中比较。 I would rather have this generate and execute a query against the db and just get me back a boolean value.
我宁愿让它生成并针对数据库执行查询,然后让我返回一个布尔值。
Is this possible to do as a property of Order entity, or do I have to write some other external query object which uses DbContext to perform these kinds of checks? 这是否可以作为Order实体的属性来完成,还是我必须编写其他一些使用DbContext执行此类检查的外部查询对象?
One way to do this is using anonymous select 一种方法是使用匿名选择
var order = dbContext.Orders
.Where(o => o.Id == id)
.Select(o => new { Order = o, HasLargeItems = o.LineItems.Count > 50 })
.SingleOrDefault();
Try this it might help: 试试这个可能会有所帮助:
public bool HasItems
{
get{return LineItems.AsQueryable().Any(x => false);}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.