[英]AutoMapper map object to any inherited destination type
lets have an DTO class: 让我们有一个DTO类:
public class UserDto {
public int Id { get;set; }
}
And viewmodel class (base mvc project library): 和viewmodel类(基本的mvc项目库):
public abstract class UserViewModelBase {
public int Id { get;set; }
}
now when i create mapping for automapper like this: 现在,当我为这样的自动映射器创建映射时:
Mapper.CreateMap<UserDto, UserViewModelBase>();
in main web mvc project i have concreate implementation of UserViewModelBase, like this: 在主要的Web MVC项目中,我已经创建了UserViewModelBase的实现,如下所示:
public class UserViewModel: UserViewModelBase {
}
Now when i call this: 现在,当我打电话给我时:
Mapper.Map<UserDto, UserViewModel>()
it fails with such error: 它失败,并显示以下错误:
Missing type map configuration or unsupported mapping. 缺少类型映射配置或不支持的映射。
UserDto -> UserViewModel UserDto-> UserViewModel
As i understand that this was caused that i havent defined direct mapping between UserDto and UserViewModel. 据我了解,这是由于我没有在UserDto和UserViewModel之间定义直接映射而引起的。 I want to know if there is some way how to tell AutoMapper that with this map
Mapper.CreateMap<UserDto, UserViewModelBase>();
我想知道是否有某种方法可以告诉AutoMapper该地图
Mapper.CreateMap<UserDto, UserViewModelBase>();
it should accept any type as destination type which inherits from UserViewModelBase
. 它应该接受从
UserViewModelBase
继承的任何类型作为目标类型。
Seems no one knows how to achieve this so i made workaround for this. 似乎没人知道如何实现这一目标,因此我为此采取了解决方法。
My workaround was to build mappings (using Mapper.CreateMap(...)
) multiple times each with concreate target class like: 我的解决方法是多次构建映射(使用
Mapper.CreateMap(...)
),每次都使用Mapper.CreateMap(...)
目标类,例如:
in ClassLibrary1: 在ClassLibrary1中:
Mapper.CreateMap<UserDto, UserViewModel1>();
in second ClassLibrary2: 在第二个ClassLibrary2中:
Mapper.CreateMap<UserDto, UserViewModel2>();
even if UserViewModel1 and UserViewModel2 is derived from same base class UserViewModelBase
. 即使UserViewModel1和UserViewModel2是从相同的基类
UserViewModelBase
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.