1

我正在尝试使用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;
    }
}

但我得到一个例外

缺少类型映射配置或不支持的映射。

映射类型:用户 -> 帐户 OpenGenerics.Console.Models.User -> OpenGenerics.Console.Models.Account

目标路径:Destination`1.Value.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>();
4

1 回答 1

2

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

Mapper.CreateMap<User, Account>();

你已经准备好了。

于 2015-08-05T15:15:32.140 回答