简体   繁体   中英

EF - related entity not loading

I've got a related entity that I use to store all my static data. Problem is, when I create a new entity, the related entity is always null. There is no issue when pulling data from the db - I can access the related entity just fine.

Using EF 6.0, model first, if that matters.

I've tried using .Include, and also re-fetching after the save, but it's not working. I'm sure it's something simple that I'm missing... any help? TIA

...
using (var db = new dbContext1())
{            
    Customer c = new Customer();
    c.id = this.id;
    db.Customer.Add(c);
    db.SaveChanges();

    for (int i = 1; i <= c.CustomerProperties.initialAllotment; i++)
    {
        //do stuff
    }
}

In the Customer class:

public int id { get; set; }    
public virtual CustomerProperties CustomerProperties { get; set; }

You are not setting CustomerProperties if you just add it and save changes then it will not be magically set by entity framework. You have to load those static properties from db and add it to your Customer and then save.

It looks like you haven't instantiated an instance of the CustomerProperties class. I would imagine using this, before the db.SaveChanges(); would fix your problem.

 c.CustomerProperties = new CustomerProperties();

Also, using CustomerProperties as the name of the class, and the name of the property may cause you some problems.

I would suggest using this instead:

 public int id { get; set; }    
 public virtual CustomerProperties customerProperties { get; set; }

Note the change from Pascal Case to Camel Case for the property's name.

See: Property Naming Guidelines

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