如何使用AutoMapper?

问题描述 投票:6回答:1

第一次使用AutoMapper,我很难弄清楚如何使用它。我正在尝试将ViewModel映射到我的数据库表。

我的ViewModel看起来像这样...

public class AddressEditViewModel
{
    public AddressEdit GetOneAddressByDistrictGuid { get; private set; }
    public IEnumerable<ZipCodeFind> GetZipCodes { get; private set; }

    public AddressEditViewModel(AddressEdit editAddress, IEnumerable<ZipCodeFind> Zips)
    {
        this.GetOneAddressByDistrictGuid = editAddress;
        this.GetZipCodes = Zips;
    }
}   

我正在尝试使用的映射是...

CreateMap<Address, AddressEditViewModel>();  

当我运行此测试时...

public void Should_map_dtos()
{
    AutoMapperConfiguration.Configure();
    Mapper.AssertConfigurationIsValid();
}  

我收到此错误...

AutoMapper.AutoMapperConfigurationException:JCIMS_MVC2.DomainModel.ViewModels.AddressEditViewModel的以下2个属性未映射:GetOneAddressByDistrictGuidGetZipCodes添加一个自定义映射表达式,忽略或重命名JCIMS_MVC2.DomainModel.Address上的属性。

我不确定如何映射这两个属性。我将不胜感激。谢谢

标记

c# automapper
1个回答
6
投票

好,所以我可以看到您正在做的一些事情可能无济于事。

首先,此AutoMapper用于将一个对象中的属性复制到diff对象中的属性。在此过程中,它可能会询问或操纵它们以使最终结果viewmodel处于正确的状态。

  1. 这些属性被命名为'Get ...',这在我看来更像是一种方法。
  2. 您属性中的设置器是私有的,因此AutoSetter将无法找到它们。将这些更改为最小内部。
  3. 使用AutoMapper时不再需要使用参数化的构造函数-因为您是直接从一个对象转换为另一个对象。参数化的构造函数主要用于显示此对象明确需要的内容。

    CreateMap<Address, AddressEditViewModel>()
             .ForMember( x => x.GetOneAddressByDistrictGuid , 
                              o => o.MapFrom( m => m."GetOneAddressByDistrictGuid") )
             .ForMember( x => x.GetZipCodes, 
                              o => o.MapFrom( m => m."GetZipCodes" ) );
    

Automapper真正擅长的是从DataObjects复制到POCO对象或View Model对象。

    public class AddressViewModel
    {
              public string FullAddress{get;set;}
    }

    public class Address
    {
              public string Street{get;set;}
              public string Suburb{get;set;}        
              public string City{get;set;}
    }

    CreateMap<Address, AddressViewModel>()
             .ForMember( x => x.FullAddress, 
                              o => o.MapFrom( m => String.Format("{0},{1},{2}"), m.Street, m.Suburb, m.City  ) );

    Address address = new Address(){
        Street = "My Street";
        Suburb= "My Suburb";
        City= "My City";
    };

    AddressViewModel addressViewModel = Mapper.Map(address, Address, AddressViewModel); 
© www.soinside.com 2019 - 2024. All rights reserved.