How do I correctly use EF4 Navigation Properties?

泄露秘密 提交于 2019-12-25 01:23:14

问题


I've created a database using the EF4 model-first approach. In my model, there's an N-to-M relationship between two entities:

I've filled my database with some dummy data, including 3 records of type Diagnosis and 3 records of type TreatmentSchema and associations between them. Here's the code snippet I used to do this:

using(var container = new SmartTherapyContainer()) {
  var diagnosisA = new Diagnosis() { Id = Guid.NewGuid(), Name = "Diagnosis A" };
  var diagnosisB = new Diagnosis() { Id = Guid.NewGuid(), Name = "Diagnosis B" };
  var diagnosisC = new Diagnosis() { Id = Guid.NewGuid(), Name = "Diagnosis C" };
  container.Diagnoses.AddObject(diagnosisA);
  container.Diagnoses.AddObject(diagnosisB);
  container.Diagnoses.AddObject(diagnosisC);

  var schemaA = new TreatmentSchema() { Id = Guid.NewGuid(), Name = "Schema 1" };
  var schemaB = new TreatmentSchema() { Id = Guid.NewGuid(), Name = "Schema 1" };
  var schemaC = new TreatmentSchema() { Id = Guid.NewGuid(), Name = "Schema 1" };
  container.Schemas.AddObject(diagnosisA);
  container.Schemas.AddObject(diagnosisB);
  container.Schemas.AddObject(diagnosisC);

  diagnosisB.TreatmentSchemas.Add(schemaA);
  diagnosisC.TreatmentSchemas.Add(schemaA);
  diagnosisC.TreatmentSchemas.Add(schemaB);
  diagnosisC.TreatmentSchemas.Add(schemaC);

  container.SaveChanges();
}

I verified that the associations are indeed stored in the reference table created through EF4's mapping. However, when I retrieve a Diagnosis via the container.Diagnoses collection later, its .TreatmentSchemas collection is always empty.

I tried debugging into the EF4-generated code and all it does is lazily create said collection, but it doesn't fill it with the associated objects. Ayende's Entity Framework Profiler shows no queries being generated at all when the property is accessed, which leads me to believe that I'm doing something wrong here.

How can I get a list of the associated TreatmentSchemas?


回答1:


Navigation properties are not loaded by default. You must use either eager loading or lazy loading but because you are using self tracking entities your choice is only eager loading because STEs don't support lazy loading. So if you want to get Diagonstic instance with all related TreatmentSchemas you must call:

var diagnosis = context.Diagnoses.Include("TreatmentSchemas").FirstOrDefault();


来源:https://stackoverflow.com/questions/5362922/how-do-i-correctly-use-ef4-navigation-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!