【问题标题】:EF Lazy Loading is Disable, But Still EF Loads Full GraphEF 延迟加载已禁用,但仍 EF 加载完整图
【发布时间】:2017-09-24 12:33:54
【问题描述】:

我使用以下代码禁用了 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 方法返回没有导航属性的对象,因为我禁用了延迟加载,但是当我运行我的代码并检查变量值时,我发现导航属性也被加载了!有谁知道可能是什么问题?

编辑

这是一个小样本

我的上下文

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:核心还是非核心?版本?
  • 实体框架6.1
  • 听起来很奇怪,给我们看一个minimal reproducible example,和/或生成的sql。
  • 还有,哪个提供商?
  • SqlClient 提供者

标签: c# entity-framework lazy-loading


【解决方案1】:

原来问题出在我的客户端代码上。当我尝试查找刚刚插入的对象时,EF 从其缓存中获取它,该缓存已与完整图一起存在,因此返回完整图。但是当我尝试 Find(1) 而不是 Find(Insert.Id) 时,它正确地返回了一个浅对象。同样在 DbSet 上使用 AsNoTracking 方法也产生了相同的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多