请参阅以下查询:
Blogs = await _context.Blog
.Include(b => b.Owner)
.ToListAsync();
此查询将加载所有博客以及每个博客的所有者(用户对象),我如何从Owener对象中加载特定字段?
例如,我只想加载Owner.Name和Owener.ID,而无需加载其他信息(电子邮件,电话,密码等)。
答案 0 :(得分:2)
手动进行;
var someData = await (
from blog in _context.Blog
join owner in _context.Users on blog.OwnerID equals owner.ID
select new { Text = blog.Text, OwnerName = owner.Name}) //select whatever you want
.ToListAsync();
这可确保仅从数据库“加载”所请求的数据。
另一种选择是从查询中进行选择,如果您使用的是延迟加载,则不能确保不会从数据库中查询数据:
var someData = await _context.Blog
.Include(b => b.Owner)
.Select(c => new { Text = c.Text, OwnerName = c.Owner.Name}) //select what needed
.ToListAsync();
var someData = await _context.Blog
.Select(c => new { Text = c.Text, OwnerName = c.Owner.Name}) //select what needed
.ToListAsync();
答案 1 :(得分:0)
您可以像这样使用 Select :
Blogs = await _context.Blog
.Include(b => b.Owner)
.Select(x => new {x.Owner.ID, x.Owner.Name})
.ToListAsync();
答案 2 :(得分:0)
您可以使用以下代码:
Blogs = await _context.Blog
.Include(b => b.Owner)
.Select(b => new
{
Name = b.Name,
Id = b.OwnerID
})
.ToListAsync();