我正在使用Entity Framework 5 Code First中的此实体类:
public class Survey
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public string SurveyName { get; set; }
[Required]
public int ClientID { get; set; }
[ForeignKey("ClientID")]
public virtual Client Client { get; set; }
}
而在我的控制器的Create方法中,我这样做:
Survey entity = new Survey()
{
SurveyName = "Test Name",
ClientID = 4
};
db.Surveys.Add(entity);
db.SaveChanges();
Client c1 = entity.Client; //Why is this null?
Client c2 = db.Clients.Find(entity.ClientID); //But this isn't?
string s2 = c2.ClientName;
string s1 = c1.ClientName; //null reference thrown here
在SaveChanges后,Client导航属性仍然为null。我原以为调用会从数据库加载Client,因为外键存在。为什么它没有这样做?
编辑
这里的代码来自于我的控制器依赖于DbContext
时。不久之后,我重构了代码,使用了存储库和工作单元。这部分移动是由于当我想要使用new
时使用Create
感觉不对。然后发生的事情是我遇到了一个问题,即如何确保在使用存储库模式时创建代理。