3

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

例如:

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"))
4

0 回答 0