c# - 在 Entity Framework Core 中禁用延迟加载
问题描述
有很多关于如何在 Entity Framework 中禁用延迟加载的帖子,但相同的技术在 EF Core 中不起作用。我LazyLoadingEnabled
在更改跟踪器中找到了该属性,但这似乎根本不起作用。
EF中的一切都指向这一点:
this.Configuration.LazyLoadingEnabled = false;
但是,Configuration
EF 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
解决方案
如果您的问题是如何使用 EF Core 禁用 LazyLoading,请尝试:
this.ChangeTracker.LazyLoadingEnabled = false;
推荐阅读
- java - Azure 数据工厂中不带冒号的格式化时间 (Java SimpleDateFormat)
- css - 如何为特定材料选择样式
- python - 使用 Pandas 从 API 构建时间序列数据集
- cakephp - 如何将 sql 查询转换为 cakephp 查询并在控制器中使用
- php - 根据 WooCommerce 购物车中的运输类别隐藏 COD 付款方式
- nlp - 如何使用自然语言处理将文本映射到预设的主题列表
- python - 如何使用 GPT-2 获取文档嵌入?
- arrays - “无效的下一个控制变量引用”错误并且似乎无法执行代码?
- java - JavaFX CEF(Java Chromium Embedded Framework)在 JPanel 中的 Swing 节点不可见
- python - 使用 regex 和 matplotlib 为给定数据绘制图形