sql server-手动键入sql以映射到c对象,就像.Include(";)方法一样

本文关键字:sql Include 一样 quot 方法 就像 server- 映射 对象 | 更新日期: 2023-09-27 18:00:31

为了简化这一点,下面是示例模型。我的模特由一位老师和许多学生组成。

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

使用EntityFramework,我可以很容易地让所有的老师和他们的学生使用linq

context.Teachers.Include("Students");

但是,如果我使用的是一个需要包含许多子属性的大型模型集,则此查询可能需要一些时间。

我的子问题是,如果我将这个linq语句链接起来,选择一个仅具有我需要的教师属性的新视图模型,然后将所有学生选择到仅具有我所需要的属性的学生视图模型中,依此类推。。这会像手动编写sql一样高效吗?Entityframework是否增加开销?

现在来谈谈我真正的问题。如何手动编写此查询以包含子属性,并以自动绑定到视图模型的方式返回它?

示例:

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

sql server-手动键入sql以映射到c对象,就像.Include(";)方法一样

要做到这一点,您根本不会使用Include,只需要使用Select:

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

例如,使用匿名类型。

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

但是您也可以声明DAO类型。