.Net Linq – 当父项可为空时如何包含子项

huangapple go评论60阅读模式
英文:

.Net Linq - How to include children when parent is nullable

问题

.Include(x => x.Parents.Select(y => y.Children))

我正在获取祖父对象,但需要包含父对象的列表,如果父对象不为空,则还需要包含其子对象的列表。出现了编译错误,因为父对象是可空的。这是有道理的,但如何为此添加条件性的 Include 呢?

这是一个相当简单的用例,但关于这方面的文档确实有点不足。


<details>
<summary>英文:</summary>


.Include(x => x.Parents.Select(y => y.Children))



I&#39;m fetching the GrandParent, but need to include the List of Parents, and if Parent is not null, include the List of its Children as well. Getting a compile error that the Parent is nullable. Which makes sense, but how to add a conditional Include for this?

Fairly simple use case but there&#39;s a surprising lack of documentation on this.



</details>


# 答案1
**得分**: 1

`ThenInclude`以Parent为根,然后使用相关的表达式项进行包含。详细信息请参考:https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager

<details>
<summary>英文:</summary>

Just do the following:

_dbContext.GrandParents
.Include(x => x.Parents)
.ThenInclude(x => x.Children)


`ThenInclude` takes Parent as root and then using expression related item(s) can be included. https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager

</details>



# 答案2
**得分**: 0

对于有类似问题的人,似乎是由于 EF 关系配置没有正确设置和父项的可空性引起的。

解决方案与Kilas的类似,只需确保包含 "!":

```csharp
.Include(x => x.Parents!)
.ThenInclude(y => y.Children)
英文:

For anyone with a similar issue, seems like this was due to EF relation configs not being properly set up and the nullability of the Parent.

Solution is similar to Kilas', just be sure to include the "!"

.Include(x =&gt; x.Parents!)
.ThenInclude(y =&gt; y.Children)

huangapple
  • 本文由 发表于 2023年6月2日 14:51:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76387783.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定