Entityframework在实体中加载列表的某些列

本文关键字:列表 加载 实体 Entityframework | 更新日期: 2023-09-27 17:58:58

嘿,假设我们有一个老师和一个学生关系,老师负责一群学生。现在,假设我想加载老师的所有信息,给定他或她的id,包括该老师负责的学生,但是,从这些学生中,我只想加载包含姓名的列,而不是年龄和学生编号(见下文)。现在我的问题是,我该怎么做?

为了解决这个问题,我发现https://colinmackay.scot/2011/07/31/getting-just-the-columns-you-want-from-entity-framework/,这与我的情况几乎相似,然而,链接中显示的示例将返回一个字符串列表,我希望在其中返回老师。

类别:

public class SchoolContext : DbContext
{
    public DbSet<Teacher> Teachers { get { return Set<Teacher>(); } }
}

public class Teacher
{
    [Key]
    public int ID { get; private set; }
    public string Name { get; set; }
    public List<Students> Students { get; set; }
}

public class Students
{
    [Key]
    public int DatabaseID { get; private set; }
    public int StudentNumber { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

加载示例:

    private static void Main(string[] args)
    {
        var Teacher = LoadTeacher(4);
        foreach(var student in Teacher.Students)
        {
           Console.WriteLine(student.Name);
        }
    }

    public static Teacher LoadTeacher(int teacherID)
    {
        using (var context = new SchoolContext())
        {
            return context.Teachers.Where(t => t.ID == teacherID)
                                   .FirstOrDefault();
                                   //At this part is my question, how would i make sure that only the name of those students are loaded and not the Age and the StudentNumber? 
        }
    }

Entityframework在实体中加载列表的某些列

您必须在上下文中选择要返回的内容。并将其作为匿名对象返回

像这样:

public static IQueryable LoadTeacher(int teacherID)
{
    using (var context = new SchoolContext())
    {
        var retVal = from teacher in context.Teachers
                     where teacher.ID == teacherID
                     select new {
                           Teacher = teacher,
                           StudentNames = from student in teacher.Students
                                          select student.Name
                           }
         return retVal;
    }
}

然后,您可以从调用方法访问此对象。

使用Select可能是哪个:

将序列的每个元素投影到一个新的表单中。

public static Teacher LoadTeacher(int teacherID)
{
    using (var context = new SchoolContext())
    {
        return context.Teachers.Where(t => t.ID == teacherID)
                                .Select(t => new Teacher() { Name = t.Name })
                                .FirstOrDefault();
    }
}

您可以使用lambda查询获得这样的学生名称

teachers.First(t => t.ID == 10).Students.SelectMany(s=> s.Name)

编辑

如果你需要教师对象以及

teachers.Where(t => t.ID == 10).Select(t=>new {teacher= t,studenNames =t.Students.SelectMany(s => s.Name) }).First()