开发者

AutoMapper determine what to map based on generic type

开发者 https://www.devze.com 2023-02-17 12:43 出处:网络
Is there a way to provide AutoMapper with just a source and based on the specified mapping for the type of that source automatically determine what to map to?

Is there a way to provide AutoMapper with just a source and based on the specified mapping for the type of that source automatically determine what to map to?

So for example I have a type of Foo and I always want it mapped to Bar but at runtime my code can receive any one of a number of generic types.

        public T Add(T entity)
        {
            //List of mappings
            var mapList = new Dictionary<Type, Type> {
                      {typeof (Foo), typeof (Bar)}
                      {typeof (Widget), typeof (Sprocket)}
                      };

            //Based on the type of T determine what we map to...somehow!
            var t = mapList[entity.GetType()];

            //What goes in ?? to ensure var in the case of Foo will be a Bar?
            var destination = AutoMapper.Mapper.Ma开发者_如何学JAVAp<T, ??>(entity);
        }

Any help is much appreciated.


As @tobsen says, the nongeneric overload is what you need:

public T Add(T entity)
    {
        //List of mappings
        var mapList = new Dictionary<Type, Type> {
                  {typeof (Foo), typeof (Bar)}
                  {typeof (Widget), typeof (Sprocket)}
                  };

        Type sourceType = typeof(T);
        Type destinationType = mapList[sourceType];
        object destination = AutoMapper.Mapper.Map(entity, sourceType, destinationType);
        // ... rest of code

    }

In my experience, the generic overload is useful only when you know the source/destination types beforehand.

0

精彩评论

暂无评论...
验证码 换一张
取 消