型破りなマッピングについて少し

多くの人が優れたAutoMapperライブラリについて知っています。 変換Entity-> Dtoでは、通常問題は発生しません。 しかし、 集約ルートがAPIに来たときに逆マッピングを処理する方法は? まあ、読み取りと書き込み-コンテキストが分離されていて、 Dtoから書き込むことができます ただし、多くの場合、IDによってORMから適切なエンティティを選択し、集計全体を保存する必要があります。 この職業は退屈ですが、多くの場合、自動化に適しています。



そのようなTypeConverterを宣言します。



public class EntityTypeConverter<TDto, TEntity> : ITypeConverter<TDto, TEntity> where TEntity: PersistentObject, new() { public TEntity Convert(ResolutionContext context) { //    DbContext // , ServiceLocator  ,      IOC        // http://stackoverflow.com/questions/4204664/automapper-together-with-dependency-injection var dc = ApplicationContext.Current.Container.Resolve<IDbContext>(); var sourceId = (context.SourceValue as IEntity)?.Id; var dest = context.DestinationValue as TEntity ?? (sourceId.HasValue && sourceId.Value != 0 ? dc.Get<TEntity>(sourceId.Value) : new TEntity()); // , reflection,         . //   Expression Trees,      //      Dto    var sp = typeof(TDto) .GetProperties(BindingFlags.Instance | BindingFlags.Public) .Where(x => x.CanRead && x.CanWrite) .ToDictionary(x => x.Name.ToUpper(), x => x); var dp = typeof(TEntity) .GetProperties(BindingFlags.Instance | BindingFlags.Public) .Where(x => x.CanRead && x.CanWrite) .ToArray(); //       foreach (var propertyInfo in dp) { var key = propertyInfo.PropertyType.InheritsOrImplements(typeof(PersistentObject)) ? propertyInfo.Name.ToUpper() + "ID" : propertyInfo.Name.ToUpper(); if (sp.ContainsKey(key)) { //     ,      propertyInfo.SetValue(dest, key.EndsWith("ID") && propertyInfo.PropertyType.InheritsOrImplements(typeof(PersistentObject)) ? dc.Get(propertyInfo.PropertyType, sp[key].GetValue(context.SourceValue)) : sp[key].GetValue(context.SourceValue)); } } return dest; } }
      
      





そして、マッピングを作成します。



 AutoMapper.Mapper .CreateMap<TDto, TEntity>() .ConvertUsing<EntityTypeConverter<TDto, TEntity>>();
      
      






All Articles