[英]Automapper and Open Generics
I'm trying to use Automapper's Open Generics as described in https://github.com/AutoMapper/AutoMapper/wiki/Open-Generics to perform a mapping between User and Account. 我正在尝试使用https://github.com/AutoMapper/AutoMapper/wiki/Open-Generics中所述的Automapper的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; }
}
I created the Source and Destination 我创建了源和目标
public class Source<T>
{
public T Value { get; set; }
}
public class Destination<T>
{
public T Value { get; set; }
}
I want to perform the mapping in an AccountService 我想在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;
}
}
But I get an exception 但是我有一个例外
Missing type map configuration or unsupported mapping.
缺少类型映射配置或不支持的映射。
Mapping types: User -> Account OpenGenerics.Console.Models.User -> OpenGenerics.Console.Models.Account
映射类型:用户->帐户OpenGenerics.Console.Models.User-> OpenGenerics.Console.Models.Account
Destination path: Destination`1.Value.Value
目标路径:Destination`1.Value.Value
Source value: OpenGenerics.Console.Models.User
源值:OpenGenerics.Console.Models.User
I confirmed the approach in https://github.com/AutoMapper/AutoMapper/wiki/Open-Generics works for int
and double
我在https://github.com/AutoMapper/AutoMapper/wiki/Open-Generics中确认了该方法可用于
int
和double
Edit This might be a solution for me, it's a little messy though. 编辑这可能对我来说是一个解决方案,但是有点混乱。
var mappingExists = Mapper.GetAllTypeMaps().FirstOrDefault(m => m.SourceType == typeof (User) && m.DestinationType == typeof (T));
if (mappingExists == null)
Mapper.CreateMap<User, T>();
For closed generics, the type parameters also need to be able to be mapped. 对于封闭的泛型,还必须能够映射类型参数。 Add this:
添加:
Mapper.CreateMap<User, Account>();
And you're set. 而且您已设定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.