首页 > 解决方案 > 在 Entity Framework Core 中禁用延迟加载

问题描述

有很多关于如何在 Entity Framework 中禁用延迟加载的帖子,但相同的技术在 EF Core 中不起作用。我LazyLoadingEnabled在更改跟踪器中找到了该属性,但这似乎根本不起作用。

EF中的一切都指向这一点:

this.Configuration.LazyLoadingEnabled = false;

但是,ConfigurationEF Core 中缺少该属性。

这是我正在谈论的一个例子:

public class TestContext : DbContext
{
    public DbSet<Person> People { get; set; }
    public DbSet<Address> Addresses { get; set; }

    public TestContext()
    {
        this.ChangeTracker.LazyLoadingEnabled = false;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {            
        var connection = new SqliteConnection($"Data Source=Test.db");
        connection.Open();

        var command = connection.CreateCommand();

        command.CommandText = $"PRAGMA foreign_keys = ON;";
        command.ExecuteNonQuery();

        optionsBuilder.UseSqlite(connection);
        optionsBuilder.UseLazyLoadingProxies(false);

        base.OnConfiguring(optionsBuilder);
    }

    private static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");

        using (var context = new TestContext())
        {
            context.Database.EnsureCreated();

            var personKey = Guid.NewGuid().ToString();
            var addressKey = Guid.NewGuid().ToString();

            context.People.Add(new Entities.Person { PersonKey = personKey, BillingAddress = new Entities.Address { AddressKey = addressKey } });
            context.SaveChanges();
        }

        using (var context = new TestContext())
        {
            var people = context.People.ToList();

            foreach (var person in people)
            {
                if (person.BillingAddress == null) throw new Exception("The billing address wasn't loaded");
            }
        }
    }
}

上面会引发异常,因为BillingAddress即使我关闭了延迟加载,也没有加载。

我怀疑这是一个错误,但请告诉我不是。我在这里记录:https ://github.com/aspnet/EntityFrameworkCore/issues/15802

您可以在此处下载示例: https ://www.dropbox.com/s/mimvgvcmibr7em2/EFSQLiteTest.7z?dl=0

标签: c#sqlite.net-coreentity-framework-core

解决方案


如果您的问题是如何使用 EF Core 禁用 LazyLoading,请尝试:

this.ChangeTracker.LazyLoadingEnabled = false;

推荐阅读