实体框架使用外键填充子对象

时间:2016-09-22 11:55:21

标签: c# entity-framework

我希望这不像我一直在寻找的那样重复,但我更多地关注这背后的原因。

我已经设置了一个用户对象。

<svg width="100" height="100">
    <g id="A">
       <path d="iconPath" fill="none"/>
       <path d="anotherPath"/>
    </g>
</svg>

和儿童对象

 typedef double v4[4];
 v4* arr = new v4[n];

当我打电话

public class User
{
    public User()
    {

    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserID { get; set; }
    public Guid UserGuid { get; set; }
    public string Email { get; set; }
    public string Name { get; set; }
    public int CompanyID { get; set; }
    public int StatusID { get; set; }
    [ForeignKey("StatusID")]
    public Status Status { get; set; }
    public int RoleID { get; set; }
    [ForeignKey("RoleID")]
    public UserRole UserRole { get; set; }
}

我将users.Status视为null,但是users.StatusID = 1。

然而,如果我打电话

public class UserRole
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int RoleId { get; set; }
    public string Role { get; set; }
}

public class Status
{
    [Key]
    public int StatusId { get; set; }
    public string Description { get; set; }
}

然后调用testuser.Status,我可以看到与StatusId相关的正确对象1.

有人可以解释为什么这会解决问题,以及如何在不事先调用以下内容的情况下使其工作。

var testuser = dbContext.User.Where(u => u.CompanyID == 1).FirstOrDefault();

由于

2 个答案:

答案 0 :(得分:2)

您可以尝试如下所示。

注意: Eager loading Include()

一起使用
  

预先加载是查询一种类型实体的过程   还会将相关实体作为查询的一部分加载

using System.Data.Entity;

var testuser = dbContext.User.Where(u => u.CompanyID == 1)
                              .Include(p => p.Status)        
                              .FirstOrDefault();

答案 1 :(得分:1)

只需像这样使用你的财产。关键字virtual将其属性设置为延迟加载,然后您可以访问整个对象。

public virtual Status Status { get; set; }

顺便说一句,我编辑了你的课程。还有一些不需要的东西,因为您可以通过属性StatusID(例如Status)访问int statID = Status.StatusID;,也可以访问UserRole。

public class User
{
    public User()
   {

   }

   [Key]
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public int UserID { get; set; }
   public Guid UserGuid { get; set; }
   public string Email { get; set; }
   public string Name { get; set; }
   public int CompanyID { get; set; }
   public virtual Status Status { get; set; }
   public virtual UserRole UserRole { get; set; }
   }
}