EF 延迟加载已禁用,但 EF 仍会加载完整图表
EF Lazy Loading is Disable, But Still EF Loads Full Graph
我使用以下代码禁用了 EF 6.1 的延迟加载
public MyContext() : base("DefaultConnection")
{
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
}
然后我使用以下行加载我的对象。
T result = (T)context.Set<T>().Find(id);
其中 T 是我域中具有某些导航属性的对象。我期望这个 Find
方法 return 没有导航属性的对象,因为我禁用了延迟加载,但是当我 运行 我的代码并检查变量值时,我发现导航属性也被加载了!有人知道问题出在哪里吗?
编辑
这是一个小样本
MyContext
public class MyContext : DbContext
{
public MyContext() : base("DefaultConnection")
{
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
}
public DbSet<Lesson> Lessons { get; set; }
public DbSet<Part> Parts { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
型号
public class Lesson
{
public int Id { get; set; }
public Part Part { get; set; }
}
public class Part
{
public int Id { get; set; }
public string Name { get; set; }
}
客户代码
using (MyContext c = new EFTest.MyContext())
{
Lesson d = new EFTest.Lesson();
d.Part = new EFTest.Part() { Name = "a" };
Lessson insert = c.Lessons.Add(d);
c.SaveChanges();
Lesson returned = c.Lessons.Find(insert.Id);
}
原来是我的客户端代码有问题。当我试图找到一个我刚刚插入的对象时,EF 从它的缓存中获取它,它已经存在于完整的图形中,因此完整的图形被返回。但是当我尝试 Find(1) 而不是 Find(Insert.Id) 时,它正确地返回了一个浅对象。同样在 DbSet 上使用 AsNoTracking 方法产生了相同的结果。
我使用以下代码禁用了 EF 6.1 的延迟加载
public MyContext() : base("DefaultConnection")
{
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
}
然后我使用以下行加载我的对象。
T result = (T)context.Set<T>().Find(id);
其中 T 是我域中具有某些导航属性的对象。我期望这个 Find
方法 return 没有导航属性的对象,因为我禁用了延迟加载,但是当我 运行 我的代码并检查变量值时,我发现导航属性也被加载了!有人知道问题出在哪里吗?
编辑
这是一个小样本
MyContext
public class MyContext : DbContext
{
public MyContext() : base("DefaultConnection")
{
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
}
public DbSet<Lesson> Lessons { get; set; }
public DbSet<Part> Parts { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
型号
public class Lesson
{
public int Id { get; set; }
public Part Part { get; set; }
}
public class Part
{
public int Id { get; set; }
public string Name { get; set; }
}
客户代码
using (MyContext c = new EFTest.MyContext())
{
Lesson d = new EFTest.Lesson();
d.Part = new EFTest.Part() { Name = "a" };
Lessson insert = c.Lessons.Add(d);
c.SaveChanges();
Lesson returned = c.Lessons.Find(insert.Id);
}
原来是我的客户端代码有问题。当我试图找到一个我刚刚插入的对象时,EF 从它的缓存中获取它,它已经存在于完整的图形中,因此完整的图形被返回。但是当我尝试 Find(1) 而不是 Find(Insert.Id) 时,它正确地返回了一个浅对象。同样在 DbSet 上使用 AsNoTracking 方法产生了相同的结果。