Base solution for your next web application
Open Closed

[Automapper] Cannot map list of entities #2166


User avatar
0
etshei created

Hi everyone,

So i have two entities BusType and Seats like these:

public class BusType : FullAuditedEntity
    {
        public virtual string name { get; set; }

        [ForeignKey("typeId")]
        public virtual ICollection<Seats> sieges { get; set; }

        public BusType()
        {

        }
    }
public class Seat : FullAuditedEntity
    {
        public virtual int number{ get; set; }

        [ForeignKey("typeId")]
        public virtual BusType type { get; set; }
        public virtual int? typeId { get; set; }

        public Seat()
        {

        }
    }

I have created DTOs the same as the main entities while replacing the properties types with corresponding DTOs (BusTypeDto,SeatDto) and the mapping is as follows:

Configuration.Modules.AbpAutoMapper().Configurators.Add(mapper =>
{
           mapper.CreateMap<BusType, BusTypeDto>();
           mapper.CreateMap<Seat, SeatDto>();
}

I try to get all the types using this method (through MVC Controller) and i get an error saying that there is a problem to map the seats property from BusType to BusTypeDto

public GetBusTypesOutput GetBusTypes(GetBusTypesInput input)
        {
            var busTypes_ = _busTypeRepository.GetAll().OrderBy(o => o.name);
            return new GetBusTypesOutput
            {
                busTypes = Mapper.Map<List<BusTypeDto>>(busTypes_)
            };
        }

the exception:

AutoMapper.AutoMapperMappingException was unhandled by user code
  HResult=-2146233088
  Message=Error mapping types.

Mapping types:
DbQuery`1 -> List`1
System.Data.Entity.Infrastructure.DbQuery`1[[BusReservationSystem.BusTypes.BusType, BusReservationSystem.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] -> System.Collections.Generic.List`1[[BusReservationSystem.BusTypes.DTOs.BusTypeDto, BusReservationSystem.Application, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]
  Source=Anonymously Hosted DynamicMethods Assembly
  StackTrace:
       at lambda_method(Closure , Object , Object , ResolutionContext )
       at BusReservationSystem.BusTypes.BusTypeService.GetBusTypes(GetBusTypesInput input) in D:\projet dev\BusReservationSystem\BusReservationSystem\BusReservationSystem.Application\BusTypes\BusTypeService.cs:line 23
       at Castle.Proxies.BusTypeServiceProxy.GetBusTypes_callback(GetBusTypesInput input)
       at Castle.Proxies.Invocations.IBusTypeService_GetBusTypes.InvokeMethodOnTarget()
       at Castle.DynamicProxy.AbstractInvocation.Proceed()
       at Abp.Domain.Uow.UnitOfWorkInterceptor.PerformSyncUow(IInvocation invocation, UnitOfWorkOptions options) in D:\Halil\Github\aspnetboilerplate\src\Abp\Domain\Uow\UnitOfWorkInterceptor.cs:line 53
       at Abp.Domain.Uow.UnitOfWorkInterceptor.PerformUow(IInvocation invocation, UnitOfWorkOptions options) in D:\Halil\Github\aspnetboilerplate\src\Abp\Domain\Uow\UnitOfWorkInterceptor.cs:line 45
       at Abp.Domain.Uow.UnitOfWorkInterceptor.Intercept(IInvocation invocation) in D:\Halil\Github\aspnetboilerplate\src\Abp\Domain\Uow\UnitOfWorkInterceptor.cs:line 35
       at Castle.DynamicProxy.AbstractInvocation.Proceed()
       at Abp.Auditing.AuditingInterceptor.PerformSyncAuditing(IInvocation invocation, AuditInfo auditInfo) in D:\Halil\Github\aspnetboilerplate\src\Abp\Auditing\AuditingInterceptor.cs:line 51
  InnerException: 
       HResult=-2146233088
       Message=Error mapping types.

Mapping types:
BusType -> BusTypeDto
BusReservationSystem.BusTypes.BusType -> BusReservationSystem.BusTypes.DTOs.BusTypeDto

Type Map configuration:
BusType -> BusTypeDto
BusReservationSystem.BusTypes.BusType -> BusReservationSystem.BusTypes.DTOs.BusTypeDto

Property:
seats
       Source=Anonymously Hosted DynamicMethods Assembly
       StackTrace:
            at lambda_method(Closure , Object , Object , ResolutionContext )
       InnerException: 
            HResult=-2146232004
            Message=An error occurred while executing the command definition. See the inner exception for details.
            Source=EntityFramework
            StackTrace:
                 at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
                 at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
                 at System.Data.Entity.Core.Objects.ObjectQuery`1.&lt;&gt;c__DisplayClass7.&lt;GetResults&gt;b__6()
                 at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
                 at System.Data.Entity.Core.Objects.ObjectQuery`1.&lt;&gt;c__DisplayClass7.&lt;GetResults&gt;b__5()
                 at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
                 at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
                 at System.Data.Entity.Core.Objects.ObjectQuery`1.Execute(MergeOption mergeOption)
                 at System.Data.Entity.Core.Objects.DataClasses.EntityCollection`1.Load(List`1 collection, MergeOption mergeOption)
                 at System.Data.Entity.Core.Objects.DataClasses.EntityCollection`1.Load(MergeOption mergeOption)
                 at System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.DeferredLoad()
                 at System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.LoadProperty[TItem](TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject)
                 at System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.<>c__DisplayClass7`2.&lt;GetInterceptorDelegate&gt;b__1(TProxy proxy, TItem item)
                 at System.Data.Entity.DynamicProxies.BusType_D2FF67FCC39115A090DE650A8FD3950AFF825BBD28B6858735278132FA682FC7.get_seats()
                 at lambda_method(Closure , Object , Object , ResolutionContext )
            InnerException: 
                 HResult=-2146233079
                 Message=There is already an open DataReader associated with this Command which must be closed first.
                 Source=System.Data
                 StackTrace:
                      at System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand command)
                      at System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String method, SqlCommand command)
                      at System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async)
                      at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
                      at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
                      at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
                      at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
                      at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
                      at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext`1 c)
                      at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
                      at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
                      at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
                      at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
                      at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
                 InnerException:

Sorry for the long post but i included as much information as needed to be understandable. In another project (0.8.3 i think and VS 2013) i used the same logic and it worked fine (now i'm using the 1.1.3 with VS2015)

Thanks in advance


2 Answer(s)
  • User Avatar
    0
    etshei created

    We resolved this problem by removing the bidirectional relation in the DTOs (removing the BusTypeDto from the SeatDto) and also using the ToList method before the mapping (it wasn't required before).

  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    Thank you for sharing your solution.