我在DTO中映射外部表属性时遇到问题。我已将源表BOOK
映射到AUTHOR
到目的地 DTO BookDTO
的导航属性,但是当我执行查询时我只从BOOK
表中获取记录。
作者:
public int Id { get; set; }
[Required]
public string Name { get; set; }
图书:
public int Id { get; set; }
[Required]
public string Title { get; set; }
public int Year { get; set; }
public decimal Price { get; set; }
public string Genre { get; set; }
// Foreign Key
public int AuthorId { get; set; }
// Navigation property
public Author Author { get; set; }
BookDTO:
public int Id { get; set; }
public string Title { get; set; }
public string AuthorName { get; set; }
映射:
Mapper.CreateMap<Book, BookDTO>()
.ForMember(dest => dest.AuthorName,
opts => opts.MapFrom(src => src.Author.Name)
);
查询:
var books = Mapper.Map<IEnumerable<BookDTO>>(db.Books).ToList().AsQueryable();
return books;
生成查询:
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Title] AS [Title],
[Extent1].[Year] AS [Year],
[Extent1].[Price] AS [Price],
[Extent1].[Genre] AS [Genre],
[Extent1].[AuthorId] AS [AuthorId]
FROM
[dbo].[Books] AS [Extent1]
答案 0 :(得分:1)
这是因为您的查询仅从Books
表中选择数据。您应该使用Include
函数来加载Author
属性:
var books = Mapper.Map<IEnumerable<BookDTO>>(db.Books.Include(x => x.Author))
.ToList()
.AsQueryable();