Entity Framework: I set the foreign key, SaveChanges then access the navigation property, but it doesn't load the related entity. Why not?

前端 未结 4 1349
再見小時候
再見小時候 2020-12-02 10:50

I am using this Entity class with Entity Framework 5 Code First:

public class Survey
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public i         


        
4条回答
  •  旧时难觅i
    2020-12-02 11:01

    To ensure that lazy loading of a navigation property will work after you've created the parent you must not create the Survey with the new operator but create it by means of the context instance because it will instantiate a dynamic proxy that is capable to lazily load the related Client. That's what the DbSet.Create() method is for:

    Survey entity = db.Surveys.Create();
    
    entity.SurveyName = "Test Name";
    entity.ClientID = 4;
    
    db.Surveys.Add(entity);
    db.SaveChanges();
    
    Client c1 = entity.Client;
    string s1 = c1.ClientName;
    // will work now if a Client with ID 4 exists in the DB
    

    Just to emphasize: It's not the line entity.ClientID = 4; or db.Surveys.Add(entity); or db.SaveChanges that loads the client from the DB, but the line Client c1 = entity.Client; (lazy loading).

提交回复
热议问题