SK2017
SK2017

Reputation: 773

Relational Data DTO in MVC Web API 2

I am new to MVC, and learning as i go, but I am struggling to get to grips with DTO's with Web api.

I have 2 tables, one Schools, one students.

The School table has a one to many relationship with the Student table.

I can't seem to get the api response the way I want it.

This is the School DTO

public class SchoolDTO
    {
        public string schoolCode { get; set; }

        public string schoolName{ get; set; }

        public string studentNames { get; set; } // the related data
}

And this is what I am trying to do to populate it -

var schoolWithStudents = from b in context.Schools
                        select new SchoolDTO()
                        {
                            schoolCode = b.schoolCode,
                            schoolName= b.schoolName,
                            studentNames = b.Student.studentName
                        };

The response i am trying to get is something like this -

School
{schoolCode, schoolName}
    StudentNames
    [{…},{..}]
}

Upvotes: 1

Views: 124

Answers (1)

koryakinp
koryakinp

Reputation: 4125

If you want to display student names which belong to a school, why studentNames property of SchoolDTO class is of type string ? It should be List<string>:

public class SchoolDTO
{
    public string schoolCode { get; set; }
    public string schoolName { get; set; }
    public List<string> studentNames { get; set; }
}

And your Database Model should be something like that:

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; }
}

So you can query the database like this:

var schoolWithStudents = context.Schools.Select(q => new SchoolDTO
{
    schoolCode = q.schoolCode,
    schoolName= q.schoolName,
    studentNames = q.Students.Select(w => w.studentName).ToList()
})
.ToList();

Upvotes: 2

Related Questions