簡體   English   中英

EF Core 排除查詢中的某些屬性,多對多關系

[英]EF Core exclude certain property in query, many-to-many relationship

如何僅在具有多對多關系的數據庫中查詢某些屬性?

所以我有一本書可以有多個作者

public class Book
{
    public Book()
    {
        Authors = new List<BookAuthor>();
    }

    public string Id { get; set; }
    public string Description { get; set; }

    public List<BookAuthor> Authors { get; set; }
}

書籍和作者的連接表

public class BookAuthor
{
    public string BookId{ get; set; }
    public string AuthorId{ get; set; }

    public Book book{ get; set; }
    public Author author{ get; set; }
}

最后,作者可以寫多本書

public class Author
{
    public string Id { get; set; }
    public string Name { get; set; }

    public List<BookAuthor> books { get; set; }

}

現在,當我想查詢一本書並返回書的 ID 和描述而不是該書的作者列表時

return await _context.Book.Select(x => new Book
        {
            Id = x.Id,
            Description = x.Description,        
        }).ToListAsync();

當我這樣做時,我得到了

{
    "id": "BOOK123",
    "description": "Stack Overflow 101",
    "Authors": []
}

我想在查詢的返回中從 Book class 中排除屬性 Author。 我如何實現這一目標?

您需要為 Book 創建一個 DTO object:

public class BookDto
{
   public string Id { get; set; }
   public string Description { get; set; }
}

然后調用:

return await _context.Book.Select(x => new BookDto
{
    Id = x.Id,
    Description = x.Description,        
}).ToListAsync();

更高級的方法是使用 Automapper ( https://automapper.org/ ) 並在您的 Book 和 BookDto 之間創建一個映射配置文件:

public class BookProfile : Profile
    {
        public BookProfile()
        {
            CreateMap<Book, BookDto>();
        }
    }

然后你可以像這樣檢索你的 BookDtos:

return await _context.Book
.ProjectTo<BookDto>(_mapper.ConfigurationProvider)
.ToListAsync();

其中 _mapper 是 IMapper 類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM