繁体   English   中英

AutoMapper - 如何修复“AutoMapperMappingException:错误映射类型”

[英]AutoMapper - How to fix "AutoMapperMappingException: Error mapping types"

我正在尝试将 map 从我的 model“ Case ”到“ CaseDTO ”。

映射时的异常:

AutoMapper.AutoMapperMappingException: Error mapping types.

Mapping types:
Case -> CaseDTO
DBR.Core.Domain.Case -> DBR.Core.DTOs.Outputs.CaseDTO

Type Map configuration:
Case -> CaseDTO
DBR.Core.Domain.Case -> DBR.Core.DTOs.Outputs.CaseDTO

Destination Member:
Workshop

---> System.InvalidOperationException: There is already an open DataReader associated with this Connection which must be closed first.
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand command)
   at Microsoft.Data.SqlClient.SqlCommand.ValidateCommand(Boolean isAsync, String method)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String method)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.InitializeReader(Enumerator enumerator)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.Load[TSource](IQueryable`1 source)
   at Microsoft.EntityFrameworkCore.Internal.EntityFinder`1.Load(INavigation navigation, InternalEntityEntry entry)
   at Microsoft.EntityFrameworkCore.Infrastructure.Internal.LazyLoader.Load(Object entity, String navigationName)
   at Microsoft.EntityFrameworkCore.Proxies.Internal.LazyLoadingInterceptor.Intercept(IInvocation invocation)
   at Castle.DynamicProxy.AbstractInvocation.Proceed()
   at Castle.Proxies.CaseProxy.get_Workshop()
   at lambda_method131(Closure , Object , CaseDTO , ResolutionContext )
   --- End of inner exception stack trace ---
   at lambda_method131(Closure , Object , CaseDTO , ResolutionContext )
   at DBR.Infrastructure.Repositories.EFRepository`4.GetAllAsync(CancellationToken cancellationToken)+MoveNext() in E:\DBR\DBR.Infrastructure\Repositories\EFRepository.cs:line 35
   at DBR.Infrastructure.Repositories.EFRepository`4.GetAllAsync(CancellationToken cancellationToken)+MoveNext() in E:\DBR\DBR.Infrastructure\Repositories\EFRepository.cs:line 27
   at DBR.Infrastructure.Repositories.EFRepository`4.GetAllAsync(CancellationToken cancellationToken)+System.Threading.Tasks.Sources.IValueTaskSource<System.Boolean>.GetResult()
   at DBR.Infrastructure.Services.Service`3.GetAllAsync(CancellationToken cancellationToken)+MoveNext() in E:\DBR\DBR.Infrastructure\Services\Service.cs:line 19
   at DBR.Infrastructure.Services.Service`3.GetAllAsync(CancellationToken cancellationToken)+MoveNext() in E:\DBR\DBR.Infrastructure\Services\Service.cs:line 19
   at DBR.Infrastructure.Services.Service`3.GetAllAsync(CancellationToken cancellationToken)+System.Threading.Tasks.Sources.IValueTaskSource<System.Boolean>.GetResult()
   at DBR.Web.Controllers.EFBaseController`3.GetAllAsync(CancellationToken cancellationToken)+MoveNext() in E:\DBR\DBR.Web\Controllers\EFBaseController.cs:line 21
   at DBR.Web.Controllers.EFBaseController`3.GetAllAsync(CancellationToken cancellationToken)+MoveNext() in E:\DBR\DBR.Web\Controllers\EFBaseController.cs:line 21
   at DBR.Web.Controllers.EFBaseController`3.GetAllAsync(CancellationToken cancellationToken)+System.Threading.Tasks.Sources.IValueTaskSource<System.Boolean>.GetResult()
   at System.Threading.Tasks.ValueTask`1.ValueTaskSourceAsTask.<>c.<.cctor>b__4_0(Object state)
--- End of stack trace from previous location ---
   at System.Text.Json.Serialization.Converters.IAsyncEnumerableOfTConverter`2.OnWriteResume(Utf8JsonWriter writer, TAsyncEnumerable value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonCollectionConverter`2.OnTryWrite(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.Converters.IAsyncEnumerableOfTConverter`2.OnTryWrite(Utf8JsonWriter writer, TAsyncEnumerable value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCoreAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteCore[TValue](JsonConverter jsonConverter, Utf8JsonWriter writer, TValue& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken)
   at System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken)
   at System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeResultAsync>g__Logged|22_0(ResourceInvoker invoker, IActionResult result)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|30_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeResultFilters>g__Awaited|28_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_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>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

HEADERS
=======
Accept: */*
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Host: localhost:44381
User-Agent: PostmanRuntime/7.29.2
Postman-Token: a99666b4-cd8b-4301-b9b3-0b112afdebf2

调试我的映射的断点

案例.cs:

public class Case : BaseEntity
{
    public Guid WorkshopId { get; set; }

    [ForeignKey(nameof(WorkshopId))]
    public virtual Workshop? Workshop { get; set; }

    public Guid CustomerId { get; set; }

    [ForeignKey(nameof(CustomerId))]
    public virtual Customer? Customer { get; set; }

    [StringLength(6)]
    public string Status { get; set; } = null!;

    public virtual ICollection<Incident>? Incidents { get; set; }
}

案例DTO:

public class CaseDTO : BaseEntity
{
    public WorkshopDTO? Workshop { get; set; }

    public CustomerDTO? Customer { get; set; }

    public string Status { get; set; } = null!;

    public List<IncidentDTO>? Incidents { get; set; }
}

映射配置文件:

public class ApplicationMapper : Profile
{
    public ApplicationMapper()
    {
        CreateMap<Address, AddressInputModel>().ReverseMap();
        CreateMap<Address, AddressDTO>();

        CreateMap<Specialization, SpecializationInputModel>().ReverseMap();
        CreateMap<Specialization, SpecializationDTO>();

        CreateMap<Workshop, WorkshopInputModel>().ReverseMap();
        CreateMap<Workshop, WorkshopDTO>();

        CreateMap<Vehicle, VehicleInputModel>().ReverseMap();
        CreateMap<Vehicle, VehicleDTO>();

        CreateMap<Customer, CustomerInputModel>().ReverseMap();
        CreateMap<Customer, CustomerDTO>();

        CreateMap<Case, CaseInputModel>().ReverseMap();
        CreateMap<Case, CaseDTO>();

        CreateMap<Incident, IncidentInputModel>().ReverseMap();
        CreateMap<Incident, IncidentDTO>();

        CreateMap<Image, ImageInputModel>().ReverseMap();
        CreateMap<Image, ImageDTO>();

        CreateMap<Invoice, InvoiceInputModel>().ReverseMap();
        CreateMap<Invoice, InvoiceDTO>();

        CreateMap<Video, VideoInputModel>().ReverseMap();
        CreateMap<Video, VideoDTO>();

        CreateMap<Attachment, AttachmentInputModel>().ReverseMap();
        CreateMap<Attachment, AttachmentDTO>();
    }
}

我试过的:

  • CreateMap<Case, CaseDTO>().ReverseMap();
  • CreateMap<Case, CaseDTO>().ForMember(dest => dest.Workshop, opt => opt.MapFrom(src => src.Workshop));
  • CreateMap<Case, CaseDTO>().ForAllMembers(options => options.Ignore());

额外信息(我的其他型号):

车间.cs:

public class Workshop : BaseEntity
{
    [StringLength(50)]
    public string Name { get; set; } = null!;

    public Guid AddressId { get; set; }

    [ForeignKey(nameof(AddressId))]
    public virtual Address? Address { get; set; }

    [StringLength(15)]
    public string PhoneNumber { get; set; } = null!;

    public virtual ICollection<Member>? Members { get; set; }

    public virtual ICollection<Case>? Cases { get; set; }

    public virtual ICollection<Specialization>? Specializations { get; set; }
}

WorkshopDTO.cs:

public class WorkshopDTO : BaseEntity
{
    public string Name { get; set; } = null!;

    public AddressDTO? Address { get; set; }

    public string PhoneNumber { get; set; } = null!;

    public List<MemberDTO>? Members { get; set; }

    public List<CaseDTO>? Cases { get; set; }

    public List<SpecializationDTO>? Specializations { get; set; }
}

客户.cs:

public class Customer : BaseEntity
{
    [StringLength(50)]
    public string Name { get; set; } = null!;

    [StringLength(15)]
    public string PhoneNumber { get; set; } = null!;

    [StringLength(50)]
    public string? Email { get; set; }

    public Guid VehicleId { get; set; }

    [ForeignKey(nameof(VehicleId))]
    public virtual Vehicle? Vehicle { get; set; }
}

客户DTO.cs:

public class CustomerDTO : BaseEntity
{
    public string Name { get; set; } = null!;

    public string PhoneNumber { get; set; } = null!;

    public string? Email { get; set; }

    public VehicleDTO? Vehicle { get; set; }
}

事件.cs:

public class Incident : BaseEntity
{
    public Guid CaseId { get; set; }

    [ForeignKey(nameof(CaseId))]
    public virtual Case? Case { get; set; }

    [StringLength(20)]
    public string? ShortId { get; set; }

    [StringLength(500)]
    public string Description { get; set; } = null!;

    [StringLength(16)]
    public string Type { get; set; } = null!;

    public virtual ICollection<Attachment>? Attachments { get; set; }
}

事件DTO.cs:

public class IncidentDTO : BaseEntity
{
    public CaseDTO? Case { get; set; }

    public string? ShortId { get; set; }

    public string Description { get; set; } = null!;

    public string Type { get; set; } = null!;

    public IEnumerable<AttachmentDTO>? Attachments { get; set; }
}

经过进一步调试(如您在帖子中的图片中所见),它出现了 InvalidOperationException。 我必须在我的连接字符串中包含MultipleActiveResultSets=True ,这一切都有效。 映射显然很好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM