简体   繁体   English

实体框架Core中的多对一映射

[英]mapping from many-to-one in entity framework Core

I have a User class我有一个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这是我的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和我的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我需要来自Blog的 select 带有图像名称和用户名

I've created this query but I don't now how to join the User class:我已经创建了这个查询,但我现在不知道如何加入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 -您还可以创建一个 DTO 类型来保存您期望的结果 -

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

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

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