Home > Blockchain >  Auto mapper with generic Class .NET Core 5
Auto mapper with generic Class .NET Core 5

Time:03-23

I have searched on Stack Overflow and googled about it but I haven't been able to find any help or suggestion on this.

I have a generic class BusinessResult<TValue> that have a value property, and I want to create an Automapper in order to map value property of BusinessResult<TSource> to value property of BusinessResult<TDestination>.

Any suggestion to do that with Automapper in .NET Core 5?

public class BusinessResult<TValue> : BusinessResult
    {
        /// <summary>
        /// Accesses the object stored in this BusinessResult.
        /// </summary>
        public TValue Value { get; set; }

        /// <summary>
        /// Creates a new empty BusinessResult, that can contain a TValue-typed value.
        /// </summary>
        public BusinessResult()
            : base()
        {

        }

        /// <summary>
        /// Creates a new BusinessResult, with the specified TValue-typed value.
        /// </summary>
        public BusinessResult(TValue value)
            : this()
        {
            Value = value;
        }
    }

CodePudding user response:

Automapper supports open generic registrations so you can create one from BusinessResult<> to BusinessResult<>:

var cfg = new MapperConfiguration(cfg =>
{
    cfg.CreateMap(typeof(BusinessResult<>), typeof(BusinessResult<>));
    cfg.CreateMap<MyClass, MyClass1>();
});
var mapper = cfg.CreateMapper();
var result = mapper.Map<BusinessResult<MyClass1>>(new BusinessResult<MyClass>(new MyClass { Value = 42 }));
Console.WriteLine(result.Value.I); // prints 42

class MyClass
{
    public int I { get; set; }
}
class MyClass1
{
    public int I { get; set; }
}
  • Related