I have two tables:
Products
ProductId | ProductName
__________|____________
1 | iPhone5
2 | iPhone6
3 | iPhone6s
Images
Id | ImagePath | ProductId
___|__________________|___________
1 | /images/231.jpg | 2
2 | /images/432.jpg | 2
3 | /images/111.jpg | 1
I want get Json looks like
{
"id":"2",
"ProductName":"iPhone6"
},
"Images":[
{
"Id":"1",
"ImagePath":"/images/231.jpg"
},
{
"Id":"2",
"ImagePath":"/images/432.jpg"
}
]
So I want to get all images of each Product using Entity Framework. I tried using join:
var ads = db.Products.
Join(db.Images,
x=>x.ProductId,
cm=>cm.ProductId,
(x ,cm) => new {
Ads = x,
Images = cm
}).
Select(d => new {
d.Ads.AdId,
d.Images.ImagePath,
}).
Where(x => x.ProductId== 2).
ToList();
And my Json
[
{
"AdId":2,
"ImagePath":"/images/231.jpg"
},
{
"AdId":2,
"ImagePath":"/images/432.jpg"
}
]
My Product and Image models:
public class Product{
public int ProductId { get; set; }
public string ProductName { get; set; }
public virtual ICollection<Image> Images { get; set; }
}
public class Image{
public int ImageId { get; set; }
public string ImagePath { get; set; }
public int ProductId { get; set; }
public virtual Product Product { get; set; }
}
Product, andImage, along with how you are modelling the relationship between these 2 entities? Because if that is done correctly, then, you don't have to perform the join, and rather need to simply grab aProduct, and serialize that (maybe usingJson.NET).