簡體   English   中英

實體框架Core中的多對一映射

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

我有一個User class

public partial class User
{
    public int Id { get; set; }
    public string UserName { get; set; }
    public virtual ICollection<Blog> Blogs { get; set; }
}

這是我的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; }
}

和我的Image class

public partial class BlogImage
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual Blog Blog { get; set; }
}

我需要來自Blog的 select 帶有圖像名稱和用戶名

我已經創建了這個查詢,但我現在不知道如何加入User class:

var blog = _context.Blog.Include(x => x.BlogImage).Include(a => a.BlogImage).ToListAsync();

嘗試 -

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

您還可以創建一個 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; }
}

然后像這樣查詢 -

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