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<T>.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).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…