通过外键访问父值

时间:2014-06-22 16:52:24

标签: c# asp.net-mvc entity-framework code-first dbcontext

型号:

public class School
{
    public int ID {Get;set;}
    public string SchoolName {get;set;}
    public virtual ICollection<Room> Rooms {get;set;}
}

public class Room
{
    public int ID {get;set;}
    public string RoomName {get;set;}

    public int SchoolID {get;set;}
    [ForeignKey("SchoolID")]
    public virtual School School {get;set;}
    public virtual ICollection<Computer> Computers {get;set;}
}

public class Computer
{
    public int ID {get;set;}
    public string ComputerName {get;set;}

    public int RoomID {get;set;}
    [ForeignKey("RoomID")]
    public virtual Room Room {get;set;}
}

所以,我有一个Computer对象并尝试访问学校名称,如:

Computer myComp = context.Computers.FirstOrDefault();
string SchoolName = myComp.School.SchoolName;

我得到一个null对象作为回报。有人能指出我正确的方向,为什么这不起作用?

1 个答案:

答案 0 :(得分:0)

在查询对象时,您需要明确告诉实体框架您要包含相关对象。以下是使用Include

执行此操作的方法
Computer myComp = context.Computers.Include(c => c.School).FirstOrDefault();

确保包含该方法所在的命名空间:

using System.Data.Entity;