ForAllMembers,根据条件映射

时间:2013-11-01 21:44:56

标签: c# automapper

需要根据属性是否出现在InvalidProperties列表中有条件地映射属性。如果列表中存在当前源属性名称,则它应使用目标值。

创建了一个解决方案,但不确定这是否是“正确的方法”:

     public class MyBassClass
      {
        public List<string> InvalidProperties
        {
          get;
          set;
        }
      }

  public class PersonAllergy : MyBassClass
  {
    public PersonAllergy()
    {
      InvalidProperties = new List<string>();
    }
    public int Id
    {
      get;
      set;
    }
    public string Allergy
    {
      get;
      set;
    }
  }
  public class Person : MyBassClass
  {
    public Person()
    {
      InvalidProperties = new List<string>();
      Allergy = new PersonAllergy();
    }

        public PersonAllergy Allergy
        {
          get;
          set;
        }
        public string FirstName
        {
          get;
          set;
        }
        public string LastName
        {
          get;
          set;
        }
        public int Age
        {
          get;
          set;
        }
      }

    private static bool IgnoreInvalid( AutoMapper.ResolutionContext context )
    {     
      return ( (MyBassClass)context.InstanceCache.First().Value )
        .InvalidProperties.Contains( context.MemberName );    
    }

用法:

  Person person = new Person();
  person.FirstName = "john";
  person.LastName = "smith";
  person.Age = 45;
  person.Allergy.Id = 1;
  person.Allergy.Allergy = "Penacilin";
  person.Allergy.InvalidProperties.Add( "Id" );
  person.InvalidProperties.Add( "Age" );
  Person templatePerson = new Person();
  templatePerson.FirstName = "sam";
  templatePerson.LastName = "rottenburg";
  templatePerson.Age = 55;
  templatePerson.Allergy.Id = 2;
  templatePerson.Allergy.Allergy = "Monkeys";

  AutoMapper.Mapper.CreateMap<Person, Person>()
    .ForAllMembers( opt => opt.Condition( IgnoreInvalid ) );
  AutoMapper.Mapper.CreateMap<PersonAllergy, PersonAllergy>()
    .ForAllMembers( opt => opt.Condition( IgnoreInvalid ) );
  var mergedPerson = AutoMapper.Mapper
    .Map<Person, Person>(templatePerson, person);
  mergedPerson.Allergy = AutoMapper.Mapper
    .Map<PersonAllergy, PersonAllergy>( templatePerson.Allergy, person.Allergy );

人员输出:

  • 年龄:45岁(而不是55岁)
  • 名字:约翰
  • 姓氏:史密斯

过敏输出:

  • 过敏:Penacillin
  • Id:2(而不是1)

0 个答案:

没有答案