4

需要根据属性是否出现在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 岁)
  • 名字:约翰
  • 姓名:史密斯

过敏输出:

  • 过敏:青霉素
  • ID:2(而不是 1)
4

0 回答 0