如何仅在相关实体上包括选定的属性 [英] How to include only selected properties on related entities
本文介绍了如何仅在相关实体上包括选定的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只能包含相关实体。
using (var context = new BloggingContext())
{
// Load all blogs, all related posts
var blogs1 = context.Blogs
.Include(b => b.Posts)
.ToList();
}
但是,我不需要整个BlogPost实体。我只对特定属性感兴趣,例如:
However, I don't need entire BlogPost entity. I'm interested only in particular properties, e.g:
using (var context = new BloggingContext())
{
// Load all blogs, all and titles of related posts
var blogs2 = context.Blogs
.Include(b => b.Posts.Select(p => p.Title) //throws runtime exeption
.ToList();
foreach(var blogPost in blogs2.SelectMany(b => b.Posts))
{
Console.Writeline(blogPost.Blog.Id); //I need the object graph
Console.WriteLine(blogPost.Title); //writes title
Console.WriteLine(blogPost.Content); //writes null
}
}
推荐答案
您可以使用 Include
加载整个实体,也可以将所需的项目投影到。选择
:
You either use Include
which loads the entire entity, or you project what you need to a .Select
:
var blogs2 = context.Blogs
.Select(x => new
{
BlogName = x.BlogName, //whatever
PostTitles = x.Post.Select(y => y.Title).ToArray()
})
.ToList();
或者,您可以执行以下操作:
Or, you could do something like this:
var blogs2 = context.Blogs
.Select(x => new
{
Blog = x,
PostTitles = x.Post.Select(y => y.Title).ToArray()
})
.ToList();
A Select
总是更好不需要整个孩子,因为它可以防止查询不需要的数据。
A Select
is always better when you don't need the entire child, as it prevents querying unneeded data.
这篇关于如何仅在相关实体上包括选定的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文