Reputation: 167
Is it possible (and how) to create map from non generic type to generic type? Assuming we have:
public interface IFoo
{
string Foo { get; set; }
}
public interface IGenericFoo<TDestination> where TDestination : class
{
string Baboon { get; set; }
}
I tried to use open generics by doing so (https://github.com/AutoMapper/AutoMapper/wiki/Open-Generics):
CreateMap(typeof(IFoo), typeof(IGenericFoo<>)
but failed in runtime with the following error:
{"The type or method has 1 generic parameter(s), but 0 generic argument(s) were provided. A generic argument must be provided for each generic parameter."}
Automapper version: 4.2.1
Upvotes: 0
Views: 4707
Reputation: 38
This only works for AutoMapper versions 5.x and higher. Here's a working example:
using AutoMapper;
using System;
public class Program
{
public class Source : IFoo
{
public string Foo { get; set; }
}
public class Destination<T> : IGenericFoo<T> where T : class
{
public string Baboon { get; set; }
}
public interface IFoo
{
string Foo { get; set; }
}
public interface IGenericFoo<TDestination> where TDestination : class
{
string Baboon { get; set; }
}
public static void Main()
{
// Create the mapping
Mapper.Initialize(cfg => cfg.CreateMap(typeof(Source), typeof(Destination<>)));
var source = new Source { Foo = "foo" };
var dest = Mapper.Map<Source, Destination<object>>(source);
Console.WriteLine(dest.Baboon);
}
}
https://dotnetfiddle.net/wpBp7k
Upvotes: 2