本文介绍了如何使用AutoMapper?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一次使用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用于将一个对象中的属性复制到Diff对象中的属性。在此过程中,它可能会询问或操作它们,以获得处于正确状态的最终结果视图模型。

  1. 属性名为‘Get.’我觉得这更像是一种方法。
  2. 属性上的setter是私有的,因此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对象,或查看模型对象。

    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);

这篇关于如何使用AutoMapper?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-17 02:29