简体   繁体   English

通过外键更新一对一关系

[英]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.

相关问题 AspNetUsers的ID作为单独表中的外键,一对一的关系 - AspNetUsers' ID as Foreign key in separate table, one-to-one relationship EF 6 - 代码首次无效的一对一外键关系 - EF 6 - Code first invalid one-to-one foreign key relationship 具有可空外键的一对一关系 - One-To-One relationship with nullable foreign keys 如何在 ASP.NET Core 6 Web API 中使用一对一关系将外键添加到表中? - How to add a foreign key into a table using one-to-one relationship in ASP.NET Core 6 Web API? 如何从与外键表一对一的关系中检索数据? - How to retrieve data from one-to-one relationship with foreign key table? 如何以一对一/零关系指定外键? - How do I specify the foreign key in a one-to-one/zero relationship? 一对一关系的更新不会保存在实体框架中 - Updating a one-to-one relationship doesn't save in entity framework 如何通过数据集插入到具有一对一关系的表中 - How to insert to table with one-to-one relationship via dataset 实体框架中的一对一外键带来巨大的性能? - HUGE performance hit with one-to-one foreign key in Entity Framework? NHibernate / Fluent的一对一映射问题:外键未更新 - One-to-one Mapping issue with NHibernate/Fluent: Foreign Key not updateing
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM