复杂的Json我有两个表:创建使用实体框架C#asp.net
产品
ProductId | ProductName
__________|____________
1 | iPhone5
2 | iPhone6
3 | iPhone6s
图片
Id | ImagePath | ProductId
___|__________________|___________
1 | /images/231.jpg | 2
2 | /images/432.jpg | 2
3 | /images/111.jpg | 1
我想要得到的Json看起来像
{
"id":"2",
"ProductName":"iPhone6"
},
"Images":[
{
"Id":"1",
"ImagePath":"/images/231.jpg"
},
{
"Id":"2",
"ImagePath":"/images/432.jpg"
}
]
所以我想获得所有图像o f使用实体框架的每个产品。我试着使用联接:
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();
而我的Json
[
{
"AdId":2,
"ImagePath":"/images/231.jpg"
},
{
"AdId":2,
"ImagePath":"/images/432.jpg"
}
]
我的产品和图像模式:
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',然后序列化(可能使用'Json.NET')。 –
已更新,请看看 –
你可能想要做一个群组加入 – Rahul