5

我的 EF 模型的一部分看起来像这样:

在此处输入图像描述

概括:

  • 位置有很多帖子
  • Post 是一个抽象
  • 讨论来源于帖子_
  • 讨论有很多评论

现在,我试图实现的查询:

获取有关位置 ID 1234 的信息,包括与这些讨论相关的任何讨论和评论。

我可以得到这样的讨论和评论:

var discussions = ctx.Posts
                     .OfType<Discussion>()
                     .Include(x => x.Comments)
                     .ToList();

但我似乎无法根据Location实体上的Posts导航来获取它。

我试过这个:

var locationWithDiscussionsAndComments = ctx
                    .Locations
                    .Include(x => x.Posts
                                   .OfType<Discussion>()
                                   .Select(y => y.Comments))
                    .SingleOrDefault();

哪个编译,但我得到错误:

System.ArgumentException:包含路径表达式必须引用实体定义的属性,还可以选择使用嵌套属性或对 Select 的调用。参数名称:路径

有任何想法吗?我可能会从帖子中“倒退”:

var locationWithDiscussionsAndComments = ctx
                   .Posts
                   .Include(x => x.Location)
                   .OfType<Discussion>()
                   .Include(x => x.Comments)
                   .Where(x => x.LocationId == 1234)
                   .Select(x => x.Location)
                   .ToList();

但就我的存储库而言,这既麻烦又语义错误(我不应该通过发布存储库来获取有关位置的信息)。

有任何想法吗?

编辑

所以在仔细考虑之后,我意识到这OfType<T>是一个过滤操作。正如我们所知,EF 不支持预加载过滤。唯一的选择是检索所有内容,或使用匿名类型投影。

我无法检索所有内容,因为涉及的元数据太多。所以我正在尝试匿名类型投影。

4

1 回答 1

6

新的Query方法可能会帮助您:

var location = context.Locations.SingleOrDefault();

context.Entry(location)
       .Collection(l => l.Posts)
       .Query()
       .OfType<Discussion>()
       .Load();


存储库实现:

我们可以向利用这个新方法的类添加一个新的LoadProperty泛型方法:Repository<T>QUery

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 方法:

Location location = _locationRepository.Find(1);
_locationRepository.LoadProperty(location, l => l.Posts, p => p is Discussion);
于 2011-03-04T16:14:07.517 回答