我正在尝试使用Automapper的开放泛型,如https://github.com/AutoMapper/AutoMapper/wiki/Open-Generics所述,以执行用户和帐户之间的映射。
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; }
}
我创建了Source和Destination
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;
}
}
但是我得到了一个异常
缺少类型映射配置或不支持映射。
映射类型:User -> Account opengeneric . console . models .User ->OpenGenerics.Console.Models.Account
目的路径:Destination ' 1.Value.Value
源值:opengeneric . console . models . user
我确认https://github.com/AutoMapper/AutoMapper/wiki/Open-Generics中的方法适用于int
和double
编辑这对我来说可能是一个解决方案,虽然有点乱。
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>();