C# EF6 LINQ 从 include() 中的子级中选择多个第二个子级

标签 c# mysql linq entity-framework-6

所以我尝试使用 LINQ 包含来自子级的多个嵌套属性

var templates = context.Templates
                        .Include(t => t.template_fields)
                        .Include(t => t.templateinstances.Select(ti => ti.templateinstance_fields))
                        .Include(t => t.templateinstances.Select(ti => ti.templateinstance_categories.Select(tic => tic.category)))
                        .ToList();

但是,当我多次包含 t.templateinstances 时,在调用 ToList() 时会收到 NullPointerException。

如果 t.templateinstances 仅包含一次,没有问题。

最佳答案

您应该检查可能为空的属性。也许应该如此;

    var templates = context.Templates
                            .Include(t => t.template_fields)
                            .Include(t => t.templateinstances.Where(ti => ti != null).Select(ti => ti.templateinstance_fields))
                            .Include(t => t.templateinstances.Where(ti => ti != null && ti.templateinstance_categories != null).Select(ti => ti.templateinstance_categories.Select(tic => tic.category)))
                            .ToList();

关于C# EF6 LINQ 从 include() 中的子级中选择多个第二个子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47429428/

相关文章:

c# - 使用 group by 和 having 的 Linq 查询

c# - 使用包括目录的 FQDN 发送电子邮件

mysql - 如何在golang中获取MySQL的BIT(64)

C# Linq 连接表,其中左表可能为空

c# - Linq 搜索不返回所有条目

c# - 尝试删除 Azure Functions 中的 blob,但缺少 DeleteIfExists 方法

c# - Sql 命令语法错误 : System. Data.SqlClient.SqlException: 'Incorrect syntax near ' ,'.'

PHP select timediff with select query and group by user

mysql - 使用 VB.NET、MySql 和 OleDbConnection 的准备语句

c# - 在 Linq c# 中安全取消引用 FirstOrDefault 调用