Automapper - 缺少外部表属性

时间:2015-03-08 07:55:53

标签: asp.net-mvc entity-framework automapper

我在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]

1 个答案:

答案 0 :(得分:1)

这是因为您的查询仅从Books表中选择数据。您应该使用Include函数来加载Author属性:

var books = Mapper.Map<IEnumerable<BookDTO>>(db.Books.Include(x => x.Author))
                .ToList()
                .AsQueryable();