加载孙子属性时是否首选这些方法之一?我喜欢第一个的简洁性,但我不知道它是否更昂贵。
return source
.Include(x => x.Server)
.Include(x => x.Server.User)
.Include(x => x.Server.ParentServer)
.Include(x => x.Server.DataCenter);
或
return source
.Include(x => x.Server)
.ThenInclude(s => s.User)
.Include(x => x.Server)
.ThenInclude(s => s.ParentServer)
.Include(x => x.Server)
.ThenInclude(s => s.DataCenter);
最佳答案
它们是等价的。第一个显然是首选,但对于集合导航来说这是不可能的。因此,ThenInclude()。
// Won't compile
return source
.Include(x => x.Posts.Authors)
.Include(x => x.Posts.Comments);
// Compiles
return source
.Include(x => x.Posts)
.ThenInclude(x => x.Authors)
.Include(x => x.Posts)
.ThenInclude(x => x.Comments);
但是,如果您想放弃编译时类型安全,也可以只使用字符串重载。
// Compiles, may throw
return source
.Include("Posts.Authors")
.Include("Posts.Comments");
但是请不要这样做......
// Over-thinking it ;-)
return source
.Include(nameof(Blog.Posts) + "." + nameof(Post.Authors))
.Include(nameof(Blog.Posts) + "." + nameof(Post.Comments));
关于linq - EF Core 中孙子属性的 Include 与 thenInclude,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58394511/