MVC Web API 2中的关系数据DTO

时间:2018-02-28 21:03:57

标签: c# asp.net-web-api asp.net-web-api2

我是MVC的新手,随时随地学习,但我很难通过Web api来掌握DTO。

我有2张桌子,一个学校,一个学生。

School表与Student表有一对多的关系。

我似乎无法按照我想要的方式获得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
    [{…},{..}]
}

1 个答案:

答案 0 :(得分:2)

如果要显示属于学校的学生姓名,为什么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();