0

I'm trying to map from my model "Case" to "CaseDTO".

Exception when it maps:

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

Debugging breakpoint of my mapping

Case.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; }
}

CaseDTO:

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; }
}

Mapping Profile:

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>();
    }
}

What I have tried:

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

Extra info (my other models):

Workshop.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; }
}

Customer.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; }
}

CustomerDTO.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; }
}

Incident.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; }
}

IncidentDTO.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; }
}

1 Answer 1

0

After further debugging (as you can see in my image in the post), it thew an InvalidOperationException. I had to include MultipleActiveResultSets=True in my connectionstring, and it all works. Mapping was fine apparently.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.