MVC Web 中的关系数据 DTO API 2
Relational Data DTO in MVC Web API 2
我是 MVC 的新手,边学边学,但我正在努力掌握 Web 的 DTO api。
我有2个table,一个学校,一个学生。
学校 table 与学生 table 具有一对多关系。
我似乎无法以我想要的方式获得 api 响应。
这是学校 DTO
public class SchoolDTO
{
public string schoolCode { get; set; }
public string schoolName{ get; set; }
public string studentNames { get; set; } // the related data
}
这就是我要填充它的方法 -
var schoolWithStudents = from b in context.Schools
select new SchoolDTO()
{
schoolCode = b.schoolCode,
schoolName= b.schoolName,
studentNames = b.Student.studentName
};
我想要得到的回应是这样的 -
School
{schoolCode, schoolName}
StudentNames
[{…},{..}]
}
如果要显示属于学校的学生姓名,为什么 SchoolDTO
class 的 studentNames 属性 是 string
类型?应该是 List<string>
:
public class SchoolDTO
{
public string schoolCode { get; set; }
public string schoolName { get; set; }
public List<string> studentNames { get; set; }
}
你的数据库模型应该是这样的:
public class School
{
[Key] //I assume it is a PK
public string schoolCode { get; set; }
public string schoolName { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
public class Student
{
[Key]
public Guid studentId { get; set; }
public string studentName { get; set; }
public string schoolCode { get; set; }
[ForeignKey("schoolCode")]
public virtual School School { get; set; }
}
所以你可以这样查询数据库:
var schoolWithStudents = context.Schools.Select(q => new SchoolDTO
{
schoolCode = q.schoolCode,
schoolName= q.schoolName,
studentNames = q.Students.Select(w => w.studentName).ToList()
})
.ToList();
我是 MVC 的新手,边学边学,但我正在努力掌握 Web 的 DTO api。
我有2个table,一个学校,一个学生。
学校 table 与学生 table 具有一对多关系。
我似乎无法以我想要的方式获得 api 响应。
这是学校 DTO
public class SchoolDTO
{
public string schoolCode { get; set; }
public string schoolName{ get; set; }
public string studentNames { get; set; } // the related data
}
这就是我要填充它的方法 -
var schoolWithStudents = from b in context.Schools
select new SchoolDTO()
{
schoolCode = b.schoolCode,
schoolName= b.schoolName,
studentNames = b.Student.studentName
};
我想要得到的回应是这样的 -
School
{schoolCode, schoolName}
StudentNames
[{…},{..}]
}
如果要显示属于学校的学生姓名,为什么 SchoolDTO
class 的 studentNames 属性 是 string
类型?应该是 List<string>
:
public class SchoolDTO
{
public string schoolCode { get; set; }
public string schoolName { get; set; }
public List<string> studentNames { get; set; }
}
你的数据库模型应该是这样的:
public class School
{
[Key] //I assume it is a PK
public string schoolCode { get; set; }
public string schoolName { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
public class Student
{
[Key]
public Guid studentId { get; set; }
public string studentName { get; set; }
public string schoolCode { get; set; }
[ForeignKey("schoolCode")]
public virtual School School { get; set; }
}
所以你可以这样查询数据库:
var schoolWithStudents = context.Schools.Select(q => new SchoolDTO
{
schoolCode = q.schoolCode,
schoolName= q.schoolName,
studentNames = q.Students.Select(w => w.studentName).ToList()
})
.ToList();