gpt4 book ai didi

c# - 基于抽象实体的预加载嵌套导航问题(EF CTP5)

转载 作者:太空狗 更新时间:2023-10-29 23:10:50 25 4
gpt4 key购买 nike

我的 EF 模型的一部分如下所示:

enter image description here

总结:

  • 位置有许多个帖子
  • 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: 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

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

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 不支持使用预加载进行过滤。唯一的选择是检索一切,或使用匿名类型投影。

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

最佳答案

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

var location = context.Locations.SingleOrDefault();

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


存储库实现:

我们可以向 Repository<T> 添加一个新的 LoadProperty 通用方法利用这个新的 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);

关于c# - 基于抽象实体的预加载嵌套导航问题(EF CTP5),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5189268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com