我对 Entity Framework 处理空对象的方式有疑问。 下面的示例是一个简单的 1 到 0..1 关系。当一个人的 Profile 不存在时,Person 对象下的 Profile 对象为空。
但是 EF 正在尝试再次执行延迟加载提取。结果,抛出 ObjectDisposedException。
public void Test()
{
Person person = null;
using (var ctx = new MainContext())
{
person = ctx.Persons
.Include(c => c.Profile);
.FirstOrDefault(p => p.Name == "Ben");
}
// ObjectDisposedException is throw here if Profile doesn't exist
var profile = person.Profile;
}
EF 似乎无法区分“不存在”和“尚未获取”。我现在最好的解决方案是禁用延迟加载。
Configuration.LazyLoadingEnabled = false;
但这会隐藏我想看到的所有 ObjectDisposedException,因为我有时可能会忘记放入 Include,现在它们都变成了 null。
处理这个问题有更好的主意吗?
最佳答案
如果你只是处理空对象,你可以在类构造函数中初始化对象,像这样:
public Person
{
this.Profile = new Profile();
}
关于c# - Entity Framework 尝试在对象为空时再次延迟加载对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35617658/