实体框架4.0自跟踪加载导航属性

时间:2011-07-25 16:08:46

标签: c#-4.0 entity-framework-4 self-tracking-entities

我有我的数据访问类的代码,我想加载他们应该有的所有患者,Patient.Addresses,Patient.Examinations,Examinations.LeftEye,Examinations.RightEye ....

如何为患者加载所有相关数据?我还没设法加载地址。

这是当前的代码:

            db.Patients.Include("Addresses");
            db.Patients.Include("Examinations");

            db.Examinations.Include("LeftEyePictures");
            db.Examinations.Include("RightEyePictures");

            List<Patient> list = db.Patients.ToList();

            list.ForEach(p => p.ChangeTracker.ChangeTrackingEnabled = true);

            return list;

谢谢。

2 个答案:

答案 0 :(得分:1)

Include必须是查询的一部分!

List<Patient> list = db.Patients.Include("Addresses")
                                .Include("Examinations.LeftEyePicutres")
                                .Include("Examinations.RightEyePicutres")
                                .ToList();

答案 1 :(得分:1)

有两种方法:  第一名:  在加载前启用lazzy加载

db.ContextOptions.LazyLoadingEnabled = true;
List<Patient> list = db.Patients.ToList(); // here is All Patients with Linked objects
db.ContextOptions.LazyLoadingEnabled = false;

然后禁用,如果你不需要它

第二:Handload

   db.Patients.Addresses.Load()
   db.Patients.Examinations.Load()
   db.Examinations.LeftEyePictures.Load()
   db.Examinations.RightEyePicturesLoad()

你可以在加载之前chesk :(这个或类似的)

   if(db.Patients.Addresses.IsLoaded==false)
      db.Patients.Addresses.Load