0

这是我的域模型的表示:

public class AddressInfo
    {
        private readonly string addressee;
        private readonly string company;
        private readonly string city;



        public string Addressee
        {
            get { return addressee; }
        }

        public string Company
        {
            get { return company; }
        }

        public string City
        {
            get { return city; }
        }
    }



 public class Address
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public AddressInfo AddressInfo { get; set; }
        }

这是我的实体类:

public class AddressEntity
{
    public  int Id { get; set; }
    public string Name { get; set; }
    public AddressInfo AddressInfo { get; set; }
}

这是我的存储库的表示,我可以在其中检索值但不能以我想要的方式映射它们。

 public class AddressRepository
    {
      public static void CreateMappings()
        {
         //How to construct a map here to take care of 
         //the map creation of AddressInfo??

         Mapper.CreateMap<AddressEntity, Address>();
        }

      public IEnumerable<Address> GetAllAddresses (User user)
        {
            var addressentities = GetAddresses(user.Id);
            return addressentities == null? 
                                 null: 
                                 Mapper.Map<IEnumerable<Address>>(addressentities);
        }


    }

如何创建地图以便处理 AddressInfo ????
目前它没有填充检索到的值,因为它显然没有映射。

4

1 回答 1

3

看起来您的AddressInfo类没有设置器或构造器参数,然后将它们设置为您的收件人、公司、城市支持变量。所以没有办法AutoMapper设置数据。

如果您想控制AutoMapper映射方式,您可以创建一个继承自TypeConverter.

//This is also easier to unit test if you have conversions that are not 100% automappable.
public class AddressEntityToAddress : TypeConverter<AddressEntity, Address>
{
    protected override Address ConvertCore(AddressEntity source)
    {
        if(source == null)
        {
            return null;
        }

        var destination = new Address
        {
            Id = source.Id,
            DisplayName = source.DisplayName,
            AddressInfo = source.AddressInfo
        };  

            //do other magic you may want during conversion time

        return destination;
    }
}

创建类型转换器类后,您可以将 AutoMapper 设置为在 CreateMapping 方法中像这样使用它:

public static void CreateMappings()
{
    Mapper.CreateMap<AddressEntity, Address>().ConvertUsing<AddressEntityToAddress>();
}
于 2013-08-07T00:12:13.757 回答