【问题标题】:How to use automap with object with nested dto?如何将自动映射与嵌套 dto 的对象一起使用?
【发布时间】:2020-11-08 16:45:51
【问题描述】:

我是 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 中使用作者实体,它可以工作,但它会给出作者拥有的帖子列表,我只想要 AuthorRead(因此 API 响应不会发送作者本身的帖子列表)。

如何将 Author 类型的对象映射到 PostRead 中的 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"));

和profiles(每一行代表相关profiles内容):

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 2012-08-06
      • 2018-10-31
      • 1970-01-01
      • 2020-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多