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

时间:2017-11-22 07:56:23

标签: 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仅包含一次,则没有问题。

2 个答案:

答案 0 :(得分:0)

您应该检查可能的null属性。应该是Perhabs;

    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();

答案 1 :(得分:0)

对于EF 6

using System.Data.Entity;

query.Include(x => x.Collection.Select(y => y.Property))

有关更多示例,请参阅Remarks

确保添加using System.Data.Entity;以获取带有lambda的Include版本。

如果您使用的是EF Core,则可以使用新方法ThenInclude

query.Include(x => x.Collection)
     .ThenInclude(x => x.Property);
相关问题