有很多关于如何在Entity Framework中禁用延迟加载的帖子,但是相同的技术在EF Core中不起作用。我在更改跟踪器中找到了LazyLoadingEnabled
属性,但这似乎根本不起作用。
在EF中,一切都指向这个:
this.Configuration.LazyLoadingEnabled = false;
但是,在EF Core中缺少Configuration
属性。
以下是我所说的示例:
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
没有被加载。
我怀疑这是一个 bug,但请告诉我不是。我已在这里记录了它:https://github.com/aspnet/EntityFrameworkCore/issues/15802
你可以在这里下载示例:https://www.dropbox.com/s/mimvgvcmibr7em2/EFSQLiteTest.7z?dl=0