[英]Foreign key with Entity Framework
我有两个模型类User和Reclamation,Relamation类有一个User对象的外键,这是我的两个类:
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时,它将很好地插入数据库中,但是我的User对象问题不包含idUser = 1的用户信息,我应该在set Property中手动编码吗在Reclamation类上的idUser属性还是我遗漏了什么?
您应该尝试以下代码:
UserData.Include("Reclamation").ToList();
您可以将虚拟属性添加到实体类以启用延迟加载。 这样,您将启用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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.