所以我尝试使用 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/