简体   繁体   中英

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:

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. 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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