Manually type sql to map to C # object just like .Include ("") method

It's easy to do here - example models. My models consist of a teacher with many students.

public class Teacher
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public List<Student> Students { get; set; }
        public Teacher()
        {
            Students = new List<Student>();
        }
    }
    public class Student
    {
        public int Id { get; set; }
        public int TeacherId { get; set; }
        [ForeignKey("TeacherId")]
        public Teacher Teacher { get; set; }
        public string Name { get; set; }
    }

      

Using EntityFramework I could easily get all teachers and their students using linq

context.Teachers.Include("Students");

      

However, if I am working with a large set of models where I need to include many child properties, this request may take a while.

My additional question is to bind this linq statement and select a new viewmodel with only the required teacher properties, and then select all students in my student viewmodel with only the properties I need, and so on. Would it be as efficient as writing sql by hand? Does Entityframework add overhead?

Now let's get to my real question. How can I write this query manually to include child properties and return it in such a way that it will automatically bind to my views?

Example:

select Teacher.Id, Teacher.Name, Student.Id, Student.Name
from Teachers
inner join Students on Teacher.Id = Student.TeacherId

      

+3


source to share


2 answers


You won't use it Include

at all for this, you just use Select

:



var query = context.Teachers.Select(teacher => new 
{
    teacher.Id,
    teacher.Name,
    Students = teacher.Students.Select(student => new
    {
        student.Id,
        student.Name,
    }
}

      

+2


source


for example with anonymous types.

var q = from t in Teachers
select new {
    Id = t.Id,
    Name = t.Name,
    Students = t.Students.Select(x => new {
        Id = x.Id,
        Name = x.Name
    })
};

      



But you can also declare DAO types.

+1


source







All Articles