Automapper 和开放泛型

Automapper and Open Generics

我正在尝试使用 https://github.com/AutoMapper/AutoMapper/wiki/Open-Generics 中所述的 Automapper 的开放泛型来执行用户和帐户之间的映射。

public class User
{
    public Guid UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime Dob { get; set; }
}

public class Account
{
    public Guid UserId { get; set; }
    public string FirstName { get; set; }
}

我创建了源和目标

public class Source<T>
{
    public T Value { get; set; }
}

public class Destination<T>
{
    public T Value { get; set; }
}

我想在 AccountService 中执行映射

public class AccountService
{
    private User user1 = new User{FirstName = "James", LastName = "Jones", Dob = DateTime.Today, UserId = new Guid("AC482E99-1739-46FE-98B8-8758833EB0D2")};

    static AccountService()
    {
        Mapper.CreateMap(typeof(Source<>), typeof(Destination<>));
    }

    public T GetAccountFromUser<T>()
    {
        var source = new Source<User>{ Value = user1 };
        var destination = Mapper.Map<Source<User>, Destination<T>>(source);
        return destination.Value;
    }
}

但是我得到一个例外

Missing type map configuration or unsupported mapping.

Mapping types: User -> Account OpenGenerics.Console.Models.User -> OpenGenerics.Console.Models.Account

Destination path: Destination`1.Value.Value

Source value: OpenGenerics.Console.Models.User

我确认 https://github.com/AutoMapper/AutoMapper/wiki/Open-Generics 中的方法适用于 intdouble

编辑 这对我来说可能是一个解决方案,但它有点混乱。

    var mappingExists = Mapper.GetAllTypeMaps().FirstOrDefault(m => m.SourceType == typeof (User) && m.DestinationType == typeof (T));
    if (mappingExists == null)
        Mapper.CreateMap<User, T>();

对于封闭泛型,类型参数也需要能够被映射。添加:

Mapper.CreateMap<User, Account>();

大功告成。