.net 自动Map器Map异常Map类型错误

5m1hhzi4  于 2023-03-24  发布在  .NET
关注(0)|答案(1)|浏览(150)

你好,我有一些问题与Automapper。
出现以下错误:
AutoMapper.AutoMapperMappingException:Map类型时出错。
Map类型:List 1 -> List 1 System.Collections.Generic.List 1[[Ordering.Domain.Aggregates.OrderAggregate.Order, Ordering.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] -> System.Collections.Generic.List 1Ordering.Application.Queries.GetOrders.OrderDto,Ordering.Application,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null---〉AutoMapper.AutoMapperMappingException:Map类型时出错。
Map类型:Order -〉OrderDto Ordering.Domain.Aggregates. OrderAggregates.Order -〉Ordering.Application.Queries.GetOrders.OrderDto
类型Map配置:Order -〉OrderDto Ordering.Domain.Aggregates. OrderAggregates.Order -〉Ordering.Application.Queries.GetOrders.OrderDto
目标成员:订单项目
---〉系统空引用异常:对象引用未设置为对象的示例。at lambda_method248(Closure,Object,List 1 , ResolutionContext ) --- End of inner exception stack trace --- at lambda_method248(Closure , Object , List 1,ResolutionContext)--- End of inner exception stack trace --- at lambda_method248(Closure,Object,List 1 , ResolutionContext ) at Ordering.Application.Queries.GetOrders.GetOrdersQueryHandler.Handle(GetOrdersQuery request, CancellationToken cancellationToken) in C:\Users\porterc\Documents\Personal Projects\LostChapters\Services\Ordering\Ordering.Application\Queries\GetOrders\GetOrdersQuery.cs:line 35 at Ordering.Application.Common.Behaviours.TransactionBehaviour 2.〈〉c__DisplayClass4_0.<b__0>d.MoveNext()in C:\Users\porterc\Documents\Personal Projects\LostChapters\Services\Ordering\Ordering.Application\Common\Behaviours\TransactionBehaviour.cs:line 50 --- End of stack trace from previous location --- at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.〈〉c.<b__3_0>d.MoveNext()---从先前位置开始的堆栈跟踪结束---在Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state,Func 4 operation, Func 4 verifySucceeded,CancellationToken cancellationToken)at Ordering.Application.Common.Behaviours.TransactionBehaviour 2.Handle(TRequest request, RequestHandlerDelegate 1 next,CancellationToken cancellationToken)in C:\Users\porterc\Documents\Personal Projects\LostChapters\Services\Ordering\Ordering.Application\Common\Behaviours\TransactionBehaviour.cs:line 41
这是我的GetOrdersQueryHandler

public GetOrdersQueryHandler(IOrderRepository orderRepository, IMapper mapper)
{
    _orderRepository = orderRepository;
    _mapper = mapper;
}

public async Task<IEnumerable<OrderDto>> Handle(GetOrdersQuery request, CancellationToken cancellationToken)
{
    var orders = await _orderRepository.GetOrders();
    var orderDtos = _mapper.Map<List<OrderDto>>(orders);

    return orderDtos;
}

下面是GetOrders方法:

public async Task<IEnumerable<Order>> GetOrders()
    {
        return await _orderingDbContext.Orders.Include(oi => oi.OrderItems).OrderBy(o => o.OrderPlaced).ToListAsync();
    }

下面是我的Order类:

public class Order : BaseEntity, IAggregateRoot
{
    
    public int OrderTotal { get; private set; }
    public DateTime OrderPlaced { get; private set; }
    public bool OrderPaid { get; private set; }
    public bool IsCancelled { get; private set; }
    public string Message { get; private set; }
    public DeliveryAddress DeliveryAddress { get; private set; }
    public OrderStatusEnum OrderStatus { get; private set; }
    public int? PaymentMethodId { get; private set; }
    public int? CustomerId { get; private set; }

    private readonly List<OrderItem> _orderItems;
    public IReadOnlyCollection<OrderItem> OrderItems => _orderItems;
    protected Order()
    {
        _orderItems = new List<OrderItem>();
        IsCancelled = false;
    }

    public Order(string userId, string userName, DeliveryAddress deliveryAddress, CardTypeEnum cardType, string cardNumber, string cardSecurityNumber,
       string cardHolderName, DateTime cardExpiration, int? customerId = null, int? paymentMethodId = null) : this()
    {
        DeliveryAddress = deliveryAddress;
        OrderStatus = OrderStatusEnum.Pending;
        OrderPlaced = DateTime.UtcNow;
        Message = "New Order Created";
        CustomerId = customerId;
        PaymentMethodId = paymentMethodId;
        AddOrderCreatedDomainEvent(userId, userName, cardType, cardNumber,
                                cardSecurityNumber, cardHolderName, cardExpiration);
    }

下面是我的OrderDto:

public record OrderDto : IMapFrom<Order>

{

public int Id { get; set; }
public string Street { get; private set; }

public string City { get; private set; }

public string Country { get; private set; }

public string PostCode { get; private set; }
public OrderStatus OrderStatus { get; set; }

private readonly List<OrderBookItemsDto> _orderItems;
public List<OrderBookItemsDto> OrderItems => _orderItems;

public void Mapping(Profile profile)
{
    profile.CreateMap<Order, OrderDto>()
        .ForMember(dto => dto.Street, opt => opt.MapFrom(p => p.DeliveryAddress.Street))
        .ForMember(dto => dto.City, opt => opt.MapFrom(p => p.DeliveryAddress.City))
        .ForMember(dto => dto.Country, opt => opt.MapFrom(p => p.DeliveryAddress.Country))
        .ForMember(dto => dto.PostCode, opt => opt.MapFrom(p => p.DeliveryAddress.PostCode))
        .ForMember(dto => dto.OrderItems, opt => opt.MapFrom(p => p.OrderItems.ToList()));   
}

}
最后是我的OrderBookItemsDto:

public record OrderBookItemsDto: IMapFrom<OrderItem>
{
public int BookCatalogueId { get; private set; }
public decimal BookPrice { get; private set; }
public string BookTitle { get; private set; }
public string Message { get; private set; }
public int Quantity { get; private set; }
public void Mapping(Profile profile)
{
    profile.CreateMap<OrderItem, OrderBookItemsDto>(); ;
}

}
有谁能指出我这里哪里错了吗?

bnl4lu3b

bnl4lu3b1#

我找到了答案:

public record OrderDto : IMapFrom<Order>
{
    public OrderDto()
    {
            _orderItems = new List<OrderBookItemsDto>();
    }

我需要在我的OrderDto中示例化0rderItems。在这里找到了答案stack overflow link

相关问题