Home > database >  How to check whether a lazy loaded collection attribute's field is null?
How to check whether a lazy loaded collection attribute's field is null?

Time:09-01

How can I check whether the lazy loaded collection field's object attribute is null in the .NET entity framework? I am thinking something like

context.Products.Include(product => product.SubProduct).Where(subProduct => subProduct.Price !- null).Where(product => keys.Contains(product.ProductId))

How can I achieve this?

CodePudding user response:

I think you may have a bit of an issue with your example.

Assuming that Price is an object reference rather than a null-able value: If you want all applicable products but only include SubProducts that have a Price assigned to them:

var products = context.Products
    .Include(product => product.SubProduct
        .Where(subProduct => subProduct.Price != null)
    .Where(product => keys.Contains(product.ProductId))
    .ToList();

If you want all products that contain a SobProduct with a Price:

var products = context.Products
    .Include(product => product.SubProduct)
    .Where(product => keys.Contains(product.ProductId)
         && product.SubProduct.Any(subProduct => subProduct.Price != null))
    .ToList();

Both of these cases are eager loading SubProducts, not lazy loading. The first example uses a filtered Include() to eager-load only the SubProducts that have a price. The second example would eager-load all SubProducts, but return only Products matchin the keys and having at least one SubProduct with a Price.

If you have an entity and are within the scope of a DbContext that is tracking it you can check whether a related reference or collection has been eager or lazy loaded (without triggering a lazy load) by using .Reference() or .Collection().

For instance if I have a Product loaded and want to check if the SubProducts (collection) are loaded:

var isLoaded = context.Entry(product).Collection(x => x.SubProduct).IsLoaded;

If the reference is a singular object reference, replace .Collection() with .Reference().

  • Related