Asp.net core AutoMapper中嵌套对象的映射类型问题

Asp.net core AutoMapper中嵌套对象的映射类型问题,asp.net-core,automapper,automapper-10,Asp.net Core,Automapper,Automapper 10,使用AutoMapper,我试图在结果中显示带有注释数组的帖子列表。然而,作为AutoMapper的新手,我遇到了一个问题,显示的评论数组中有不必要的信息。我试图在PostDTO中使用CommentDTO,但在使用它时,出现了映射类型的错误。相反,我添加了另一个CreateMap,但它在PostDTO中不起作用。你能告诉我如何处理这个问题吗 型号 // post public class Post { public int Id { get; set; }

使用AutoMapper,我试图在结果中显示带有注释数组的帖子列表。然而,作为AutoMapper的新手,我遇到了一个问题,显示的评论数组中有不必要的信息。我试图在PostDTO中使用CommentDTO,但在使用它时,出现了映射类型的错误。相反,我添加了另一个CreateMap,但它在PostDTO中不起作用。你能告诉我如何处理这个问题吗

型号

// post
   public class Post
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public int EmployeeId { get; set; }
        public Employee Employee { get; set; }

        public IList<Comment> Comments { get; set; }
    }

// Comment
 public class Comment
    {
        [Key]
        public int Id { get; set; }
        public string text { get; set; }
        public int EmployeeId { get; set; }
        public int PostId { get; set; }

        public virtual Employee Employee { get; set; }
        public virtual Post Post { get; set; }
    }

public List<PostDTO> GetAllPosts()
        {
            var posts = _context.Posts
                .Include(x => x.Employee)
                .ThenInclude(x => x.Organization)
                .Include(x =>x.Comments)
                .ToList();
            List<PostDTO> result = _mapper.Map<List<Post>, List<PostDTO>>(posts);

            return result;
        }
预期结果

[
  {
    "id": 1,
    "title": "Test1",
    "author": "Tom",
    "orgName": "A",
    "comments": [
      {
        "id": 1,
        "text": "Good",
        "employeeId": 1,
        "postId": 1,
        "employee": {
          "id": 1,
          "name": "Tom",
          "organizationId": 1,
          "organization": {
            "id": 1,
            "name": "A",
            "employees": [
              {
                "id": 2,
                "name": "Kevin",
                "organizationId": 1,
                "posts": [
                  {
                    "id": 4,
                    "title": "Test4",
                    "employeeId": 2,
                    "comments": []
                  }
                ],
                "comments": [
                  {
                    "id": 2,
                    "text": "Bad",
                    "employeeId": 2,
                    "postId": 1,
                    "post": {
                      "id": 1,
                      "title": "Test1",
                      "employeeId": 1,
                      "comments": []
                    }
                  }
                ]
              }
            ]
          },
          "posts": [
            {
              "id": 1,
              "title": "Test1",
              "employeeId": 1,
              "comments": [
                {
                  "id": 2,
                  "text": "Bad",
                  "employeeId": 2,
                  "postId": 1,
                  "employee": {
                    "id": 2,
                    "name": "Kevin",
                    "organizationId": 1,
                    "organization": {
                      "id": 1,
                      "name": "A",
                      "employees": []
                    },
                    "posts": [
                      {
                        "id": 4,
                        "title": "Test4",
                        "employeeId": 2,
                        "comments": []
                      }
                    ],
                    "comments": []
                  }
                }
              ]
            .....
[
  {
    "id": 1,
    "title": "Test1",
    "author": "Tom",
    "orgName": "A",
    "comments": [
      {
       "id": 1,
       "Text": "Nicee",
       "CommentAuthor": "Kevin"
      },
    ]
   },
...
错误

AutoMapper.AutoMapperMappingException: Error mapping types.

Mapping types:
List`1 -> List`1
System.Collections.Generic.List`1[[Persistence.Models.Post, Persistence, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] -> System.Collections.Generic.List`1[[Application.DTO.PostDTO, Application, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]
 ---> AutoMapper.AutoMapperMappingException: Error mapping types.

Mapping types:
Post -> PostDTO
Persistence.Models.Post -> Application.DTO.PostDTO

Type Map configuration:
Post -> PostDTO
Persistence.Models.Post -> Application.DTO.PostDTO

Destination Member:
Comments

 ---> AutoMapper.AutoMapperMappingException: Error mapping types.

Mapping types:
IList`1 -> IList`1
System.Collections.Generic.IList`1[[Persistence.Models.Comment, Persistence, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] -> System.Collections.Generic.IList`1[[Application.DTO.CommentDTO, Application, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]
 ---> AutoMapper.AutoMapperMappingException: Error mapping types.

Mapping types:
Comment -> CommentDTO
Persistence.Models.Comment -> Application.DTO.CommentDTO

Type Map configuration:
Comment -> CommentDTO
Persistence.Models.Comment -> Application.DTO.CommentDTO

Destination Member:
CommentAuthor

 ---> System.FormatException: Input string was not in a correct format.
   at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
   at lambda_method(Closure , IList`1 , IList`1 , ResolutionContext )
   --- End of inner exception stack trace ---
   at lambda_method(Closure , IList`1 , IList`1 , ResolutionContext )
   --- End of inner exception stack trace ---
   at lambda_method(Closure , IList`1 , IList`1 , ResolutionContext )
   at lambda_method(Closure , List`1 , List`1 , ResolutionContext )
   --- End of inner exception stack trace ---
   at lambda_method(Closure , List`1 , List`1 , ResolutionContext )
   --- End of inner exception stack trace ---
   at lambda_method(Closure , List`1 , List`1 , ResolutionContext )
   at Application.Services.GetAllPosts() in C:\Users\sbaek\Documents\Dev\.NET Core LINQ_210605\210605\Application\Services.cs:line 32
   at WebAPI.Controllers.BlogController.GetAllPost() in C:\Users\sbaek\Documents\Dev\.NET Core LINQ_210605\210605\WebAPI\Controllers\BlogController.cs:line 26
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at NSwag.AspNetCore.Middlewares.SwaggerUiIndexMiddleware.Invoke(HttpContext context)
   at NSwag.AspNetCore.Middlewares.RedirectToIndexMiddleware.Invoke(HttpContext context)
   at NSwag.AspNetCore.Middlewares.OpenApiDocumentMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)


AutoMapper.AutoMapperMappingException:错误映射类型。
映射类型:
列表'1->列表'1
System.Collections.Generic.List`1[[Persistence.Models.Post,Persistence,Version=1.0.0,Culture=neutral,PublicKeyToken=null]->System.Collections.Generic.List`1[[Application.DTO.PostDTO,Application,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null]]
--->AutoMapper.AutoMappingException:错误映射类型。
映射类型:
Post->PostDTO
Persistence.Models.Post->Application.DTO.PostDTO
类型映射配置:
Post->PostDTO
Persistence.Models.Post->Application.DTO.PostDTO
目的地成员:
评论
--->AutoMapper.AutoMappingException:错误映射类型。
映射类型:
IList`1->IList`1
System.Collections.Generic.IList`1[[Persistence.Models.Comment,Persistence,Version=1.0.0,Culture=neutral,PublicKeyToken=null]->System.Collections.Generic.IList`1[[Application.DTO.CommentDTO,Application,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null]]
--->AutoMapper.AutoMappingException:错误映射类型。
映射类型:
评论->评论到
Persistence.Models.Comment->Application.DTO.CommentDTO
类型映射配置:
评论->评论到
Persistence.Models.Comment->Application.DTO.CommentDTO
目的地成员:
评论作者
--->System.FormatException:输入字符串的格式不正确。
at System.Number.ThrowOverflowOrFormatException(ParsingStatus状态,类型代码类型)
在lambda_方法(闭包,IList`1,IList`1,ResolutionContext)
---内部异常堆栈跟踪的结束---
在lambda_方法(闭包,IList`1,IList`1,ResolutionContext)
---内部异常堆栈跟踪的结束---
在lambda_方法(闭包,IList`1,IList`1,ResolutionContext)
at lambda_方法(闭包,列表'1,列表'1,ResolutionContext)
---内部异常堆栈跟踪的结束---
at lambda_方法(闭包,列表'1,列表'1,ResolutionContext)
---内部异常堆栈跟踪的结束---
at lambda_方法(闭包,列表'1,列表'1,ResolutionContext)
在C:\Users\sbaek\Documents\Dev\.NET核心LINQ\u 210605\210605\Application\Services.cs中的Application.Services.GetAllPosts()处:第32行
在C:\Users\sbaek\Documents\Dev\.NET核心LINQ\u 210605\210605\WebAPI\Controllers\BlogController.GetAllPost()中:第26行
在lambda_方法(闭包、对象、对象[])
位于Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(对象目标,对象[]参数)
位于Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper映射器、ObjectMethodExecutor执行器、对象控制器、对象[]参数)
在Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()中
位于Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(状态和下一步、范围和范围、对象和状态、布尔值和isCompleted)
在Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()上
---来自引发异常的上一个位置的堆栈结束跟踪---
位于Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed上下文)
位于Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(状态和下一步、范围和范围、对象和状态、布尔值和isCompleted)
在Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()中
---来自引发异常的上一个位置的堆栈结束跟踪---
在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g_|24_0(ResourceInvoker invoker、Task lastTask、State next、Scope Scope、Object State、Boolean isCompleted)
位于Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed上下文)
位于Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(状态和下一步、范围和范围、对象和状态、布尔值和isCompleted)
在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()中
---来自引发异常的上一个位置的堆栈结束跟踪---
在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g|u waiting | 17|0(ResourceInvoker invoker,Task Task,IDisposable作用域)
位于Microsoft.AspNetCore.Routing.EndpointMiddleware.g_uwaitRequestTask | 6_0(端点、任务请求任务、ILogger记录器)
位于NSwag.AspNetCore.middleware.SwaggerUiIndexMiddleware.Invoke(HttpContext上下文)
位于NSwag.AspNetCore.middleware.RedirectToIndexMiddleware.Invoke(HttpContext上下文)
位于NSwag.AspNetCore.middleware.OpenApiDocumentMiddleware.Invoke(HttpContext上下文)
位于Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext上下文)
位于Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext上下文)

您的
CommentDTO
有一个属性
int CommentAuthor
,它是从
Employee.Name
映射而来的,我假设它是一个
字符串。听起来您需要将
CommentAuthor
a
string

[
  {
    "id": 1,
    "title": "Test1",
    "author": "Tom",
    "orgName": "A",
    "comments": [
      {
       "id": 1,
       "Text": "Nicee",
       "CommentAuthor": "Kevin"
      },
    ]
   },
...
AutoMapper.AutoMapperMappingException: Error mapping types.

Mapping types:
List`1 -> List`1
System.Collections.Generic.List`1[[Persistence.Models.Post, Persistence, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] -> System.Collections.Generic.List`1[[Application.DTO.PostDTO, Application, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]
 ---> AutoMapper.AutoMapperMappingException: Error mapping types.

Mapping types:
Post -> PostDTO
Persistence.Models.Post -> Application.DTO.PostDTO

Type Map configuration:
Post -> PostDTO
Persistence.Models.Post -> Application.DTO.PostDTO

Destination Member:
Comments

 ---> AutoMapper.AutoMapperMappingException: Error mapping types.

Mapping types:
IList`1 -> IList`1
System.Collections.Generic.IList`1[[Persistence.Models.Comment, Persistence, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] -> System.Collections.Generic.IList`1[[Application.DTO.CommentDTO, Application, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]
 ---> AutoMapper.AutoMapperMappingException: Error mapping types.

Mapping types:
Comment -> CommentDTO
Persistence.Models.Comment -> Application.DTO.CommentDTO

Type Map configuration:
Comment -> CommentDTO
Persistence.Models.Comment -> Application.DTO.CommentDTO

Destination Member:
CommentAuthor

 ---> System.FormatException: Input string was not in a correct format.
   at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
   at lambda_method(Closure , IList`1 , IList`1 , ResolutionContext )
   --- End of inner exception stack trace ---
   at lambda_method(Closure , IList`1 , IList`1 , ResolutionContext )
   --- End of inner exception stack trace ---
   at lambda_method(Closure , IList`1 , IList`1 , ResolutionContext )
   at lambda_method(Closure , List`1 , List`1 , ResolutionContext )
   --- End of inner exception stack trace ---
   at lambda_method(Closure , List`1 , List`1 , ResolutionContext )
   --- End of inner exception stack trace ---
   at lambda_method(Closure , List`1 , List`1 , ResolutionContext )
   at Application.Services.GetAllPosts() in C:\Users\sbaek\Documents\Dev\.NET Core LINQ_210605\210605\Application\Services.cs:line 32
   at WebAPI.Controllers.BlogController.GetAllPost() in C:\Users\sbaek\Documents\Dev\.NET Core LINQ_210605\210605\WebAPI\Controllers\BlogController.cs:line 26
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at NSwag.AspNetCore.Middlewares.SwaggerUiIndexMiddleware.Invoke(HttpContext context)
   at NSwag.AspNetCore.Middlewares.RedirectToIndexMiddleware.Invoke(HttpContext context)
   at NSwag.AspNetCore.Middlewares.OpenApiDocumentMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)