如何对带有嵌套dto的对象使用自动映射?

时间:2020-11-08 16:45:51

标签: c# asp.net-core automapper automapper-10

我是Automap的新手,我试图过滤出结果。我想知道如何映射嵌套的dto。

发布实体:


public class Post
{

    public Author? Author { get; set; }
    [Required] [Key] public int Id { get; set; }
    [Required] public string Title { get; set; }
    [Required] public string Description { get; set; }
    [Required] public string Body { get; set; }
}

后读:(dto)

public class PostRead
{
    public DateTime Created { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
    public string Description { get; set; }
    // Author would work but I want only the AuthorRead data
    public AuthorRead Author;
}

作者实体

public class Author
{
    [Key] [Required] public int Id { get; set; }

    [Required] public string Name { get; set; }

    public IEnumerable<Post> Posts { get; set; }
}

AuthorRead.cs(dto)

public class AuthorRead
{
    public int Id { get; set; }
    public string Name { get; set; }
}

从技术上讲,如果我在 PostRead 中使用Author Entity,它可以工作,但它会列出Author拥有的帖子列表,而我只需要 AuthorRead < / em>(因此API响应不会发送Author本身的帖子列表)。

如何在PostRead中将Author类型的对象映射到AuthorRead类型?

错误:

AutoMapper.AutoMapperMappingException : Missing type map configuration or unsupported mapping.

Mapping types:
Object -> PostRead
System.Object -> OhMyBlogAPI.Models.PostRead
   at lambda_method22(Closure , Object , PostRead , ResolutionContext )
   at OhMyBlogAPI.Tests.AutomapTests.MockPost_MapsTo_PostRead() in

我尝试了什么,并进行了大量搜索。

CreateMap<Post, PostRead>()
                .ForMember(m
                    => m.Author, o
                    => o.MapFrom<Author, AuthorRead>("Author"));

和配置文件(每行代表相关的配置文件内容):

CreateMap<Post, PostRead>();
CreateMap<Author, AuthorRead>();

1 个答案:

答案 0 :(得分:0)

糟糕,代码有效。 我在单元测试中配置错误。真的很抱歉。