[英]Updating One-to-One relationship via foreign key
I've got a small application where I use a EF CodeFirst approach. 我有一个使用EF CodeFirst方法的小型应用程序。 One on the model have one-to-one relationship vith another one. 模型上的一个与另一个具有一对一的关系。 Here is an example 这是一个例子
public class Customer
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id {get; set;}
public string Name {get; set;}
public int PersonInfoId {get; set;}
public virtual Person PersonInfo {get; set;}
}
public class Person
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id {get; set;}
public string Name {get; set;}
//Some other properties
}
I create a new Customer and set ParentId to existing one 我创建一个新的Customer并将ParentId设置为现有的
Customer superCustomer = new Customer();
superCustomer.PersonInfoId = 21;
customersContext.Customers.Add(superCustomer);
When I try to select this customer I've got all data but navigation property is null. 当我尝试选择此客户时,我拥有所有数据,但导航属性为null。
var c = customersContext.Customers.Where(x => x.Id == 1).FirstOrDefault(x=>x);
c.Person //is null :(
But if I restart application and than select this particular customer the navigation property will be filled with dymamic proxy as usual in EF. 但是,如果我重新启动应用程序,然后选择该特定客户,则导航属性将像往常一样在EF中填充动态代理。 It looks like EF does nit retriev navigation property until context is recreated. 似乎EF确实检索了导航属性,直到重新创建上下文为止。 Is there any way to fix this? 有没有什么办法解决这一问题?
尝试以下方法:
var c = customersContext.Customers.Inclue(x=>x.PersonInfo).Where(x => x.Id == 1).FirstOrDefault(x=>x);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.