简体   繁体   English

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

[英]C# EF6 LINQ Select multiple 2nd childs from child in include()

So I'm trying to include multiple nested properties from a child with LINQ 所以我正在尝试从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();

But when I include t.templateinstances more than once, I get a NullPointerException when the ToList() call is made. 但是,当我多次包含t.templateinstances时,调用ToList()时会收到NullPointerException。

There is no problem if t.templateinstances is only included once. 如果仅包含一次t.templateinstances,则没有问题。

You should check possible null properties. 您应该检查可能的空属性。 Perhabs it should be; 也许应该;

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

For EF 6 对于EF 6

using System.Data.Entity;

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

See Remarks for more examples. 有关更多示例,请参见备注

Make sure to add using System.Data.Entity; 确保using System.Data.Entity;添加using System.Data.Entity; to get the version of Include that takes in a lambda. 获得Include lambda的Include版本。


If you are using EF Core you can use the new method ThenInclude 如果您使用的是EF Core,则可以使用新方法ThenInclude

query.Include(x => x.Collection)
     .ThenInclude(x => x.Property);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM