我是MVC的新手,边走边学,但我正在努力掌握DTO的Web api。
我有2张桌子,一张学校,一张学生。
">学校"表与"学生"表具有一对多关系。
我似乎无法以我想要的方式获得 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
类的 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();