I have a User
class
public partial class User
{
public int Id { get; set; }
public string UserName { get; set; }
public virtual ICollection<Blog> Blogs { get; set; }
}
and this is my Blog
class
public partial class Blog
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int? PostedBy { get; set; }
public virtual User { get; set; }
public virtual ICollection<BlogImage> BlogImages { get; set; }
}
and my Image
class
public partial class BlogImage
{
public int Id { get; set; }
public string Name { get; set; }
public virtual Blog Blog { get; set; }
}
I need to select from Blog
with image Name and UserName
I've created this query but I don't now how to join the User
class:
var blog = _context.Blog.Include(x => x.BlogImage).Include(a => a.BlogImage).ToListAsync();
Try -
var blog = await _context.Blog
.Select(p => new
{
Id = p.Id,
Title = p.Title,
Content = p.Content,
PostedBy = p.PostedBy,
UserName = p.User.UserName,
ImageNames = p.BlogImages.Select(x => x.Name).ToList()
})
.ToListAsync();
You can also create a DTO type to hold the result you are expecting -
public class BlogDTO
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int? PostedBy { get; set; }
public string UserName { get; set; }
public List<string> ImageNames { get; set; }
}
and then query like -
BlogDTO blogDTO = await _context.Blog
.Select(p => new BlogDTO
{
Id = p.Id,
Title = p.Title,
Content = p.Content,
PostedBy = p.PostedBy,
UserName = p.User.UserName,
ImageNames = p.BlogImages.Select(x => x.Name).ToList()
})
.ToListAsync();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.