指定complextype的映射表达式

时间:2016-12-13 16:20:18

标签: c# automapper

我正在尝试使用AutoMapper将XElement映射到Item实体。 该项具有两个具有相同复杂类型的属性。应该从不同的属性映射这些属性。

class Identity
{
    public int ID { get; set; }
    public  int Name { get; set; }
}

class Item
{
    public Identity Identity { get; set; }
    public Identity Identity2 { get; set; }
}

class ItemProfile : Profile
{
    public ItemProfile()
    {
        var IdentityMapping = CreateMap<XElement, Identity>()
            .ForMember(dest => dest.ID, opt => opt.MapFrom(s => s.Attribute("id").Value))
            .ForMember(dest => dest.Name, opt => opt.MapFrom(s => s.Attribute("name").Value));

        var Identity2Mapping = CreateMap<XElement, Identity>()
            .ForMember(dest => dest.ID, opt => opt.MapFrom(s => s.Attribute("item_id").Value))
            .ForMember(dest => dest.Name, opt => opt.MapFrom(s => s.Attribute("item_name").Value));            

        CreateMap<XElement, Item>()
            .ForMember(dest => dest.Identity, /*How to use IdentityMapping?*/)
            .ForMember(dest => dest.Identity2, /*How to use Identity2Mapping?*/);
    }
}

[TestClass]
public class ItemTests
{
    [TestMethod]
    public void SouldMapItem()
    {
        IMapper mapper = new MapperConfiguration(cfg => cfg.AddProfile(new ItemProfile())).CreateMapper();
        var doc = XElement.Parse(@"<item id='1' name='one' item_id='10' item_name='ten'></item>");
        var item = mapper.Map<Item>(doc);
        Assert.IsNotNull(item);            
    }
}

如何为ItemProfile中的每个Identity属性指定映射?

0 个答案:

没有答案