user888734 user888734 - 5 months ago 27
C# Question

EntityFramework - get list of Products, each with List of Images

Suppose I have a table of Products in a database, and a table of ProductImages, with corresponding models like so:

public class Product {
public int Id {get;set;}
public List<ProductImage> Images {get;set;}

public class ProductImage {
public int Id {get; set;}
public int ProductId {get;set;}
public string Url {get;set;}}

Obviously, I can get a list of products like so:

var query = from p in db.Product select p;

How could I get a list of products such that each ProductModel's Images property has been populated with the images with matching ProductId?


Use Include, this ensures that the related entities are also retrieved.

var query = from p in db.Product.Include(x => x.Images) select p;

This assumes that you mapped the relationship between Product and ProductImage and as there is no mention of it not being mapped I believe this assumption is valid.