我将我的应用程序从 EF4.1 更新到 EF6,现在我遇到了延迟加载问题。我使用 EF6.x DbContext Generator 生成新的 DbContext。来自这个 article 的所有建议也适用。
- 我的类(class)是公开的
- 不密封,不抽象
- 有一个公共(public)构造函数
- 既不实现
IEntityWithChangeTracker
也不实现IEntityWithRelationships
ProxyCreationEnabled
和LazyLoadingEnabled
都设置为 true- 导航属性是虚拟的
在我看来也很奇怪的是,如果我使用 Include("...")
显式包含导航属性,它就会被加载。
我的 POCO 和 DbContext 的简化版本:
public partial class Ideation
{
public Ideation()
{
}
public long Id { get; set; }
public Nullable<long> ChallengeId { get; set; }
public virtual Challenge Challenge { get; set; }
}
public partial class Challenge
{
public Challenge()
{
this.Ideations = new HashSet<Ideation>();
}
public long Id { get; set; }
public virtual ICollection<Ideation> Ideations { get; set; }
}
public partial class BoxEntities : DbContext
{
public TIBoxEntities()
: base("name=BoxEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Ideation> Ideations { get; set; }
public virtual DbSet<Challenge> Challenges { get; set; }
}
我还尝试显式设置 ProxyCreationEnabled
和 LazyLoadingEnabled
但没有成功。正如此调试 session 屏幕截图所示,该实体未作为动态代理加载:
我还缺少什么?
最佳答案
可能发生这种情况的情况是,您尝试使用 Find
加载的实体已经作为非代理对象附加到上下文。例如:
using (var context = new MyContext())
{
var ideation = new Ideation { Id = 1 }; // this is NOT a proxy
context.Ideations.Attach(ideation);
// other stuff maybe ...
var anotherIdeation = context.Ideations.Find(1);
}
anotherIdeation
将是已经附加的非代理,它不能延迟加载。使用 var anotherIdeation = context.Ideations.SingleOrDefault(i => i.Id == 1);
运行数据库查询甚至无济于事,因为查询的默认合并选项是 AppendOnly
,即只有在不存在具有该键的附加实体时才会添加新实体。所以,anotherIdeation
仍然是一个非代理。
在 GetById
方法中调用 Find
之前,您可以使用 Local
检查实体是否已附加:
bool isIdeationAttached = context.Ideations.Local.Any(i => i.Id == id);
关于c# - EF6 延迟加载不起作用,而急切加载工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22152700/