user888734 user888734 - 1 year ago 93
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download