Entity Framework 的外键

Foreign key with Entity Framework

我有两个模型 classes User 和 Reclamation,Reclamation class 有一个 User 对象的外键,这是我的两个 classes :

public class User
{
    [Key, ScaffoldColumn(false), Display(Name = "ID User")]
    public int idUser { set; get; }

    [Required, StringLength(16), Display(Name = "Login")]
    public string login { set; get; }

    [Required, StringLength(16), Display(Name = "Password")]
    public string password { set; get; }
}

public class Reclamation
{
    [Key, ScaffoldColumn(false), Display(Name = "ID Reclamation")]
    public int idReclamation { set; get; }

    [ForeignKey("idUser")]
    public User user{ set; get; }

    [Required, Display(Name = "ID Rapporteur")]
    public int idUser { set; get; }

    [Required, StringLength(30), Display(Name = "Message")]
    public string message{ set; get; }
}

例如,假设我有一个 idUser=1 的用户。当我用 idUser=1 创建一个新的 Reclamation 时,它会很好地插入数据库,但我的用户对象问题它不包含 idUser=1 的用户信息,我应该在集合中手动编码 属性 Reclamation 上的 idUser 属性 class 或者我遗漏了什么?

你应该试试这个代码:

UserData.Include("Reclamation").ToList();

您可以将虚拟 属性 添加到您的实体 class 以启用延迟加载。这样您就可以让 EF 在请求时加载相关对象。

        public class User
        {
            [Key, ScaffoldColumn(false), Display(Name = "ID User")]
            public int idUser { set; get; }

            [Required, StringLength(16), Display(Name = "Login")]
            public string login { set; get; }

            [Required, StringLength(16), Display(Name = "Password")]
            public string password { set; get; }

            public virtual Reclamation Reclamation {get; set;}

            /*if you have one to many relationship, use Collection<T> 
   and initialize it in the constructor Reclamations = new Collection<Reclamation>();*/
            public virtual Collection<Reclamation> Reclamations {get; set;}
        }

您的另一个选择是使用预先加载,如上所述。类似于:

context.Users.Include(x => x.Reclamations).ToList();