【发布时间】:2019-07-18 14:11:31
【问题描述】:
假设您在大型数据库中具有完全定义的书籍和作者关系以及许多其他关系
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
...
Public int AuthorId { get; set; }
Public Author Author { get; set; }
}
public class Author
{
public int Id { get; set; }
public int GroupId { get; set; }
public string Name { get; set; }
...
public List<Book> Books { get; set; }
...
}
在您的控制器中,您希望返回一个作者列表,每个作者都包含使用 DTO 与他们关联的书籍列表。
public class BookDTO
{
public int Id { get; set; }
public string Title { get; set; }
}
public class AuthorDTO
{
public int Id { get; set; }
public string Name { get; set; }
public List<BookDTO> Books { get; set; }
}
在 DTO 中生成 DTO 列表的正确方法是什么?
你能做这样的事吗?
var author = from a in _context.authors.Where(a => a.groupId == someGroup)
select new AuthorDTO()
{
Id = a.Id,
Name = a.Name,
Books = (from b in a.Books
select new BookDTO()
{
Id = b.Id,
Title = b.Title
}).ToList()
};
或者可能是这样的?
var author = from a in _context.authors.Where(a => a.groupId == someGroup)
select new AuthorDTO()
{
Id = a.Id,
Name = a.Name,
Books = (from b in _context.books.Where(b => b.AuthorId == a.AuthorId)
select new BookDTO()
{
Id = b.Id,
Title = b.Title
}).ToList()
};
编辑:
为了更清楚一点,我在这里重新表述并提出了我的问题:
【问题讨论】:
-
那么,您希望所有图书按作者分组吗?
-
是的,基本上就是这样:返回特定作者列表
_context.authors.Where(a => a.groupId == someGroup)以及一些信息,每个作者 DTO 都包含他们的书籍列表。 -
所以这是按作者分组的书籍,但我希望书籍列表位于每个作者对象中,并返回该作者列表
标签: c# asp.net-core linq-to-sql entity-framework-core dto