关于如何在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
。
我怀疑这是一个错误,但请告诉我不是。我在这里记录了它:https://github.com/aspnet/EntityFrameworkCore/issues/15802
您可以在此处下载示例: https://www.dropbox.com/s/mimvgvcmibr7em2/EFSQLiteTest.7z?dl=0
答案 0 :(得分:0)
如果您的问题是禁用EF Core的LazyLoading,请尝试: this.ChangeTracker.LazyLoadingEnabled = false;