Two things:
- You only need to use .Include(x => x.SomeProperty) when you're letting EF construct the entities, not when you're selecting a NEW object. EF will automatically interpret your select and wire in the nested property data.
Example when you need to include so that product.ProductImages is populated:
var p = _context.Product
// Without this include, the products in the return list will all have null
// ProductImages property.
.Include(p => p.ProductImages)
.ToList(); // A list of products WITH their ProductImages property populated.
Example when you don't need to use include (derived object / anonymous object) (obviously untested against your model):
var p = _context.Product
.Select(p => new { // This could be a defined object too such as ProductSearch...
p.Id,
p.Name,
MyDirectImages = p.ProductImages
// You don't need to filter to this products images because the
// ProductImages navigation property is ALREADY only images for this product.
.Where(i => i.IsDefault && p.ProductVariationId == null)
.ToList(), // OK, could be .FirstOrDefault() as well if only expecting one.
MyVariations = p.ProductVariations
.Select(v => new {
v.Id,
v.Name,
// Once again, the VariationImages (I'm guessing the name...) navigation
// property is already only images for this variation.
ImageUrl = v.VariationImages.Where(x => x.IsDefault).FirstOrDefault().ImageUrl
}).ToList();
})
.ToList(); // A list of information about products
- Without addressing the other superfluous includes, you can do this for your specific question:
Replace
ImageUrl = p.ProductImages.Any() ? p.ProductImages.First().ImageUrl : "PARENT IMAGE NEEDED HERE"
with
ImageUrl = p.ProductImages.Any() ? p.ProductImages.First().ImageUrl : p.Product.ProductImages.Where(x => x.IsDefault && x.ProductVariationId == null).FirstOrDefault().ImageUrl
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…