如何在Entity Framework 5中正确触发集合的延迟加载? [英] How to properly trigger lazy load of collection in Entity Framework 5?
问题描述
我在应用程序中使用EF5(代码优先)。
我有一个包含一些延迟加载字段的表。
I'm using EF5 (code first) in my application. I have a table which contains a few lazy loading fields.
public class TestEntity
{
public int Id { get; set; }
public virtual TestEntity2 SubEntity2 { get; set; }
public virtual TestEntity3 SubEntity3 { get; set; }
private ICollection<SubEntity4> _subEntities;
public ICollection<SubEntity4> SubEntities
{
get { return _subEntities ?? (_subEntities = new Collection<SubEntity4>()); }
protected set { _subEntities = value; }
}
}
当我从数据库SubEntity2和SubEntity3可以很好地加载,但是SubEntities集合不会加载,并且始终保持Count = 0。所以我强迫这样的负载:
When I'm reading this from database SubEntity2 and SubEntity3 are loading fine but SubEntities collection just won't load and it's always stay Count=0. So I'm forcing load like this:
db.Entry(queryResult).Collection(rr => rr.SubEntities).Load();
但是据我了解,此集合应该在第一次调用时由EF自动加载,就像SubEntity2和SubEntity3 。为什么它不能与集合一起使用?
But as I understand this collection should be loaded automatically by EF during the first invocation just like SubEntity2 and SubEntity3. Why isn't it working with collection?
我用来读取数据库的代码示例:
Example of the code I'm using to read database:
using (var db = new TestContext(_connection, false))
{
var query = from r in db.SubEntities
where r.Id == 10
select r;
var queryRes = query.FirstOrDefault();
if (queryRes != null)
{
if (queryRes.FederalRegion != null)
{
// Do something
}
foreach (var dbEnt in queryRes.SubEntities)
{
// Do something
}
}
}
推荐答案
为了使延迟加载正常工作,EF5必须做一些棘手的工作。在运行时,它们创建代理类,这些代理类是从模型类派生的。在这些代理类中,它们重写导航属性以实现延迟加载机制。
In order for lazy-loading to work, EF5 has to do some tricky work. At runtime they create proxy-classes, which are derived from your model classse. Within these proxy classes they override the navigation properties to implement the lazy-loading mechanism.
您的 SubEntity2
和 SubEntity3
属性是虚拟的,因此可以覆盖它们。您的 SubEntities
属性不是虚拟的-EF5无法覆盖此属性以对其进行延迟加载。
Your SubEntity2
and SubEntity3
properties are virtual, so they can be overridden. Your SubEntities
property is not virtual - EF5 can't override this property to implement lazy loading for it.
何时您将您的 SubEntities
属性设置为虚拟,就可以使用。
When you make your SubEntities
property virtual it should work.
这篇关于如何在Entity Framework 5中正确触发集合的延迟加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!