简体   繁体   中英

Updating One-to-One relationship via foreign key

I've got a small application where I use a EF CodeFirst approach. 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 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.

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. It looks like EF does nit retriev navigation property until context is recreated. Is there any way to fix this?

尝试以下方法:

var c = customersContext.Customers.Inclue(x=>x.PersonInfo).Where(x => x.Id == 1).FirstOrDefault(x=>x);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM