基于抽象的实体与预先加载嵌套导航问题(EF CTP5) [英] Problem with Eager Loading Nested Navigation Based on Abstract Entity (EF CTP5)
问题描述
我看起来像这样我的EF模型的部分内容:
I a portion of my EF model that looks like this:
摘要:
- 地点有许多文章
- 邮政是一个摘要类
- 讨论的导出从发表
- 讨论许多注释
- Location has many Posts
- Post is an abstract class
- Discussion derives from Post
- Discussions have many Comments
现在,查询我试图实现的:
Now, the query i'm trying to achieve:
获取有关地点标识1234,包括与相关的任何讨论和评论信息这些讨论
我能得到讨论,这样的评论:
I can get discussions and the comments like this:
var discussions = ctx.Posts
.OfType<Discussion>()
.Include(x => x.Comments)
.ToList();
但我似乎无法得到它的基础上的文章导航。在位置实体
我试过这样:
var locationWithDiscussionsAndComments = ctx
.Locations
.Include(x => x.Posts
.OfType<Discussion>()
.Select(y => y.Comments))
.SingleOrDefault();
其中编译,但我得到的错误:
Which compiles, but i get the error:
System.ArgumentException:include路径表达式必须是指由实体定义的属性,也可选择嵌套的属性或调用来选择。
参数名称:路径
System.ArgumentException: The include path expression must refer to a property defined by the entity, optionally also with nested properties or calls to Select. Parameter name: path
任何想法?我大概可以走倒退,从文章:
Any ideas? I could probably go "backwards" from the Posts:
var locationWithDiscussionsAndComments = ctx
.Posts
.Include(x => x.Location)
.OfType<Discussion>()
.Include(x => x.Comments)
.Where(x => x.LocationId == 1234)
.Select(x => x.Location)
.ToList();
但是,这既是毛茸茸和语义错误的,我库而言(我不应该去通过岗位信息库,以获取有关位置的信息)。
But that is both hairy and semantically wrong in terms of my repositories (i shouldn't have to go through a post repository to get information about a location).
任何想法?
修改
因此,有一个更大的思考后,我意识到, OfType< T>
是一个过滤器操作。正如我们所知,EF不支持与预先加载过滤。唯一的选择是检索家居或使用匿名类型的投影。
So after having a bigger think about it, i realized that OfType<T>
is a filter operation. As as we know, EF does not support filtering with eager loading. The only options are retrieving everything, or using anonymous type projection.
没有办法,我可以检索的一切,因为有太多的元数据参与其中。所以我试图匿名类型的投影
No way i can retrieve everything, as there is far too much meta data involved. So i'm attempting the anonymous type projection.
推荐答案
新的查询的方法可以帮助你:
The new Query method might help you:
var location = context.Locations.SingleOrDefault();
context.Entry(location)
.Collection(l => l.Posts)
.Query()
.OfType<Discussion>()
.Load();
结果
我们可以添加一个新的 LoadProperty 的泛型方法到库< T>
类它利用这个新的查询
方法:
We can add a new LoadProperty generic method to the Repository<T>
class that leverages this new QUery
method:
public void LoadProperty<TElement>(T entity,
Expression<Func<T, ICollection<TElement>>> navigationProperty,
Expression<Func<TElement, bool>> predicate) where TElement : class
{
_context.Set<T>().Attach(entity);
_context.Entry(entity)
.Collection(navigationProperty)
.Query()
.Where(predicate)
.Load();
}
使用LoadProperty方法:
Using the LoadProperty method:
Location location = _locationRepository.Find(1);
_locationRepository.LoadProperty(location, l => l.Posts, p => p is Discussion);
这篇关于基于抽象的实体与预先加载嵌套导航问题(EF CTP5)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!