AutoMapper map IdPost to Post

点点圈 提交于 2019-12-06 08:29:31

You could define AfterMap action to load entities using NHibernate in your mapping definition. I'm using something like this for simmilar purpose:

        mapperConfiguration.CreateMap<DealerDTO, Model.Entities.Dealer.Dealer>()
            .AfterMap((src, dst) =>
                {
                    if (src.DepartmentId > 0)
                        dst.Department = nhContext.CurrentSession.Load<CompanyDepartment>(src.DepartmentId);
                    if (src.RankId > 0)
                        dst.Rank = nhContext.CurrentSession.Load<DealerRank>(src.RankId);
                    if (src.RegionId > 0)
                        dst.Region = nhContext.CurrentSession.Load<Region>(src.RegionId);
                });

you can do this easily with the ValueInjecter

it would be something like this:

//first you need to create a ValueInjection for your scenario
      public class IntToPost : LoopValueInjection<int, Post>
        {
            protected override Post SetValue(int sourcePropertyValue)
            {
                return Session.Load(sourcePropertyValue);
            }
        }

// and use it like this
post.InjectFrom(new IntToPost().SourcePrefix("Id"), postDto);

also if you always have the prefix Id than you could set it in the constructor of the IntToPost and use it like this:

post.InjectFrom<IntToPost>(postDto);
epitka
  1. Create a new Id2EntityConverter

    public class Id2EntityConverter<TEntity> : ITypeConverter<int, TEntity> where TEntity : EntityBase
    {
        public Id2EntityConverter()
        {
            Repository = ObjectFactory.GetInstance<Repository<TEntity>>();
        }
    
        private IRepository<TEntity> Repository { get; set; }
    
        public TEntity ConvertToEntity(int id)
        {
            var toReturn = Repository.Get(id);
            return toReturn;
        }
    
        #region Implementation of ITypeConverter<int,TEntity>
    
        public TEntity Convert(ResolutionContext context)
        {
            return ConvertToEntity((int)context.SourceValue);
        }
    
        #endregion
    }
    
  2. Configure AM to auto create maps for each type

    public class AutoMapperGlobalConfiguration : IGlobalConfiguration
    {
        private AutoMapper.IConfiguration _configuration;
    
        public AutoMapperGlobalConfiguration(IConfiguration configuration)
        {
            _configuration = configuration;
        }
    
        public void Configure()
        {
            //add all defined profiles
            var query = this.GetType().Assembly.GetExportedTypes()
                .Where(x => x.CanBeCastTo(typeof(AutoMapper.Profile)));
    
            _configuration.RecognizePostfixes("Id");
    
            foreach (Type type in query)
            {
                _configuration.AddProfile(ObjectFactory.GetInstance(type).As<Profile>());
            }
    
            //create maps for all Id2Entity converters
            MapAllEntities(_configuration);
    
           Mapper.AssertConfigurationIsValid();
        }
    
        private static void MapAllEntities(IProfileExpression configuration)
        {
            //get all types from the my assembly and create maps that
            //convert int -> instance of the type using Id2EntityConverter
            var openType = typeof(Id2EntityConverter<>);
            var idType = typeof(int);
            var persistentEntties = typeof(MYTYPE_FROM_MY_ASSEMBLY).Assembly.GetTypes()
               .Where(t => typeof(EntityBase).IsAssignableFrom(t))
               .Select(t => new
               {
                   EntityType = t,
                   ConverterType = openType.MakeGenericType(t)
               });
            foreach (var e in persistentEntties)
            {
                var map = configuration.CreateMap(idType, e.EntityType);
                map.ConvertUsing(e.ConverterType);
            }
        }
    }
    

Pay attention to MapAllEntities method. That one will scan all types and create maps on the fly from integer to any type that is of EntityBase (which in our case is any persistent type). RecognizePostfix("Id") in your case might be replace with RecognizePrefix("Id")

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!