本文介绍了AutoMapper将IdPost映射到Post的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据规则将DTO上的ind IdPost映射到Blog对象上的Post对象.

I'm trying to map int IdPost on DTO to Post object on Blog object, based on a rule.

我想实现这一目标:BlogDTO.IdPost => Blog.Post

I would like to achieve this: BlogDTO.IdPost => Blog.Post

帖子将由NHibernate加载:Session.Load(IdPost)

Post would be loaded by NHibernate: Session.Load(IdPost)

如何使用AutoMapper实现这一目标?

How can I achieve this with AutoMapper?

推荐答案

  1. 创建一个新的Id2EntityConverter

  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
}

  • 配置AM以针对每种类型自动创建地图

  • 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);
            }
        }
    }
    

  • 请注意MapAllEntities方法.那将扫描所有类型并动态创建从整数到EntityBase的任何类型(在我们的情况下为任何持久性类型)的映射.您的情况下的RecognizePostfix("Id")可能会替换为RecognizePrefix("Id")

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

    这篇关于AutoMapper将IdPost映射到Post的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    06-18 01:44