[英]How do I correctly use EF4 Navigation Properties?
I've created a database using the EF4 model-first approach. 我使用EF4模型优先方法创建了一个数据库。 In my model, there's an N-to-M relationship between two entities:
在我的模型中,两个实体之间存在N对M的关系:
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. 我用一些虚拟数据填充了我的数据库,包括3个类型为
Diagnosis
记录和3个类型为TreatmentSchema
记录以及它们之间的关联。 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. 我验证了关联确实存储在通过EF4映射创建的引用表中。 However, when I retrieve a
Diagnosis
via the container.Diagnoses
collection later, its .TreatmentSchemas
collection is always empty. 但是,当我稍后通过
container.Diagnoses
集合检索Diagnosis
时,其.TreatmentSchemas
集合始终为空。
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. 我尝试调试EF4生成的代码,它所做的只是懒惰地创建所述集合,但它没有用相关对象填充它。 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.
Ayende的Entity Framework Profiler显示在访问该属性时根本没有生成任何查询,这让我相信我在这里做错了。
How can I get a list of the associated TreatmentSchemas
? 如何获得相关
TreatmentSchemas
的列表?
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 .
您必须使用预先加载或延迟加载,但因为您使用自我跟踪实体,您的选择只是急切加载,因为STE不支持延迟加载 。 So if you want to get Diagonstic instance with all related TreatmentSchemas you must call:
因此,如果您想获得所有相关TreatmentSchemas的Diagonstic实例,您必须致电:
var diagnosis = context.Diagnoses.Include("TreatmentSchemas").FirstOrDefault();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.