我想学习这样做,因为它让我头疼:S
目标:
进行尽可能少的数据库查询以获取我的应用程序的逻辑 JSON 对象。
设想
家长可以为孩子支付活动费用的学校应用程序。一个家长有很多学生,一个学生有很多行项目(订单),一个行项目作为学生和产品之间的连接表。
楷模:
public class Parent
{
public int ParentId { get; set; }
public string FullName { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
public class Student
{
public int StudentId { get; set; }
public string FullName { get; set; }
public int ParentId { get; set; }
public virtual Parent Parent { get; set; }
public virtual ICollection<LineItem> LineItems { get; set; }
}
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public virtual ICollection<LineItem> LineItems { get; set; }
}
public class LineItem
{
public int Id { get; set; }
public int ProductId { get; set; }
public int StudentId { get; set; }
public int Discount {get; set;}
// ...
public virtual Product Product { get; set; }
public virtual Student Student { get; set; }
}
我想生成的 JSON:
{
"Parent": {
"ParentId": 10,
"FullName": "John Doe",
"Students": [
{
"StudentId": 12,
"FullName": "William Doe",
"ParentId": 10,
"LineItems": [
{
"Discount": 10,
"Price": 150,
"Name": "Student trip to Washington"
},
{
"Discount": 10,
"Price": 20,
"Name": "Halloween party"
}
]
},
{
"StudentId": 15,
"FullName": "Kate Mary-Jane Doe",
"ParentId": 10,
"LineItems": [
{
"Discount": 10,
"Price": 110,
"Name": "Spring Break to Mexico"
}
]
}
]
}
}
笔记:
我已经尝试过 View Models 和 AutoMapper,但我无法获得所有内容的嵌套输出。我能做的最好的事情是获得一个嵌套的 Parent -> Students[] 输出,但无法弄清楚如何到达 LineItems 和 Products。