我正在尝试从OrderResource自动映射到我的订单。我的OrderResource
public class OrderResource
{
public string OrderId { get; set; }
public UserResource User { get; set; }
public double TotalOrder { get; set; }
public IEnumerable<OrderItemResource> OrderItems { get; set; }
public OrderResource()
{
OrderItems = new List<OrderItemResource>();
}
}
OrderItemResource:
public class OrderItemResource
{
public string ProductName { get; set; }
public double Price { get; set; }
public int Quantity { get; set; }
public OrderResource Order { get; set; }
public string OrderId { get; set; }
}
我的订单模型。这就是我想将包含项目的OrderResource映射到:
[Table("Orders")]
public class Order
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Mail { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public double Cost { get; set; }
public IEnumerable<OrderItem> Items { get; set; }
public Order()
{
Items = new List<OrderItem>();
}
}
和我的OrderItem模型:
[Table("OrderItems")]
public class OrderItem
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
public int Quantity { get; set; }
[ForeignKey("OrderId")]
public Order Order { get; set; }
public int OrderId { get; set; }
}
在映射用户等方面我没有任何麻烦。它们都可以工作,但是我不知道如何映射OrderItems。这是令我失望的最后一行:
CreateMap<OrderResource, Services.Order.Models.Order>()
.ForMember(o => o.Id, opt => opt.Ignore())
.ForMember(o => o.Mail, opt => opt.MapFrom(or => or.OrderId))
.ForMember(o => o.FirstName, opt => opt.MapFrom(or => or.User.firstName))
.ForMember(o => o.LastName, opt => opt.MapFrom(or => or.User.lastName))
.ForMember(o => o.Address, opt => opt.MapFrom(or => or.User.adress))
.ForMember(o => o.Items, opt => opt.MapFrom(or => or.OrderItems));
确切的错误出现在这里:
Services.Order.Models.Order realOrder = Mapper.Map<OrderResource, Services.Order.Models.Order>(Order);
错误是AutoMapperMappingException:缺少类型映射配置或不支持的映射。
更新:
我现在添加了:
CreateMap<OrderItemResource, OrderItem>()
.ForMember(oir => oir.Name, opt => opt.MapFrom(oi => oi.ProductName))
.ForMember(oir => oir.Price, opt => opt.MapFrom(oi => oi.Price))
.ForMember(oir => oir.Quantity, opt => opt.MapFrom(oi => oi.Quantity));
我怎么称呼它? 我的控制器中有这个
Services.Order.Models.Order realOrder = Mapper.Map<OrderResource, Services.Order.Models.Order>(Order);
,但是它在自动映射时仍然不使用orderitem数组。