【发布时间】:2016-07-28 17:24:48
【问题描述】:
嘿,假设我们有一个老师和一个学生关系,老师负责一组学生。现在假设我想加载老师的所有信息,给定他或她的 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?
}
}
【问题讨论】:
标签: c# entity-framework