Entityframework使用实体

时间:2016-07-28 07:34:46

标签: c# entity-framework

Heey,让我们假设我们有一个老师和一个学生的关系,老师负责一群学生。现在让我说我想加载教师的所有信息,考虑到他或她的身份,包括这位老师负责的学生,但是从那些学生我只想加载包含姓名的专栏,所以不是年龄和StudentNumber(见下文)。现在我的问题是,我该怎么做?

为了解决这个问题,我找到了这个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? 

        }
    }

3 个答案:

答案 0 :(得分:1)

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

像这样:

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

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

答案 1 :(得分:0)

使用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();
    }
}

答案 2 :(得分:0)

您可以使用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()