当源中不存在属性时的自动映射映射

时间:2016-08-02 17:56:02

标签: c# automapper

我正在尝试使用Automapper将ViewModel映射到Domain类。

但是,ViewModel包含Domain类中不存在的属性。

相反,我使用不同的属性Product,从Domain类映射到ViewModel Price属性,但这似乎不起作用。

public class OrderViewModel
{
    public IEnumerable<Product> Product { get; set; }

    public IEnumerable<Price> Price { get; set; }

}

public class Order
{
    public IEnumerable<Product> Product { get; set; }
}

public class Product
{
    public string Code { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }

    public decimal Amount { get; set; }

    public decimal DeliveryCharge { get; set; }

}

public class Price
{
    public string UniqueProductCode { get; set; }

    public decimal Charge { get; set; }

    public decimal CourierCharge { get; set; }

}

然后在我的映射配置文件中,我设置了以下内容:

public class DomainToViewModelMappingProfile : Profile
    {
        public override string ProfileName
        {
            get
            {
                return "DomainToViewModelMappings";
            }
        }

        public DomainToViewModelMappingProfile()
        {
            ConfigureMappings();
        }


        /// <summary>
        /// Creates a mapping between source (Domain) and destination (ViewModel)
        /// </summary>
        private void ConfigureMappings()
        {

           CreateMap<Core.Domain.Product, Web.Models.Price>()
               .ForMember(dest => dest.UniqueProductCode,
                          opts => opts.MapFrom(src => src.Code))
               .ForMember(dest => dest.Charge,
                          opts => opts.MapFrom(src => src.Amount))
               .ForMember(dest => dest.CourierCharge,
                          opts => opts.MapFrom(src => src.DeliveryCharge));

    CreateMap<Core.Domain.Order, OrderViewModel>()
                    .ForMember(dest => dest.Product, 
                               opts => opts.MapFrom(src => src.Product))
                    .ForMember(dest => dest.Price,
                               opts => opts.MapFrom(src => new List<Price>() ));
        }
    }

然后在我的控制器中我有:

var list = _productRepository.GetProducts();
Mapper.Map<Order, OrderViewModel>(list );

但是Price属性为空(非空),因为该属性已被实例化。只是没有记录。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

private void dataGridCustomers_SelectionChanged(object sender, SelectionChangedEventArgs args)
{
    if (args.AddedItems.Length > 0)
    {
        Customer selectedCustomer = (Customer) args.AddedItems[0];
        MessageBox.Show(selectedCustomer.FirstName);
    }
}

表示您正在设置dest.Price = new List();试试这个:

.ForMember(dest=>dest.Price, opts=>opts.MapFrom(src=>new List<Price>()));