自动映射 - 将对象数组映射到单个对象

时间:2012-05-07 17:51:11

标签: c#-4.0 mapping automapper

我想将对象数组映射到一个对象。

例如:

public class ArrayData
{
  //name of property in class MyObject in upper under score casing
  public string PropName{get;set;}

  //value of property in class MyObject
  public string PropValue{get;set;}
}

来源数据:

ArrayData [] sourceData = new ArrayData[]{new ArrayData{PropName="MY_ID",PropValue="1"}}

目标对象:

public class MyObject
{
  public int MyId{get;set;}
}

我的目标是将MyObject.MyId设置为1。

公约是:

if(ArrayData.PropName == MyObject.Property.Name)
{
   MyObject.PropName = ArrayData.PropValue;
}

编辑:我试过这种方式:

public class UpperUnderscoreNamingConvention : INamingConvention
{
    #region Implementation of INamingConvention

    public Regex SplittingExpression
    {
        get { throw new System.NotImplementedException(); }
    }

    public string SeparatorCharacter
    {
        get { return string.Format("_"); }
    }

    #endregion
}

public class TestProfile: Profile
{
    public override string ProfileName { get { return "TestProfile"; } }
    protected override void Configure()
    {
        SourceMemberNamingConvention = new UpperUnderscoreNamingConvention();
        DestinationMemberNamingConvention = new PascalCaseNamingConvention();

        CreateMap<ArrayData, MyObject>()
                           .ForMember(dest => dest.MyId, opt =>
                                            {
                                                opt.Condition(src => src.ColumnName == "MY_ID");
                                                opt.MapFrom(src => src.Value);
                                            });
    } 
}

转换:

        Mapper.Initialize((obj) => obj.AddProfile(new TestProfile()));

        var myClass = Mapper.Map<ArrayData[], MyClass>(sourceData);

它不起作用,我得到了这个例外:

  

AutoMapper.AutoMapperMappingException:缺少类型映射配置   或不支持的映射。

此外,我认为这不是一个好的解决方案,可以手动绘制所有属性:

 .ForMember(dest => dest.MyId, opt => opt.Condition(src => src.ColumnName =="MY_ID"))

0 个答案:

没有答案