c# - 具有相同属性名称的 AutoMapper 双向映射

标签 c# automapper-3

给定这两个对象

public class UserModel
{
    public string Name {get;set;}
    public IList<RoleModel> Roles {get;set;}
}

public class UserViewModel 
{
    public string Name {get;set;}
    public IList<RoleViewModel> Roles {get;set;} // notice the ViewModel
}

这是进行映射的最佳方式,还是 AutoMapper 能够自行将 Roles 映射到 Roles

应用配置

Mapper.CreateMap<UserModel, UserViewModel>()
    .ForMember(dest => dest.Roles, opt => opt.MapFrom(src => src.Roles));
Mapper.CreateMap<UserViewModel, UserModel>()
    .ForMember(dest => dest.Roles, opt => opt.MapFrom(src => src.Roles));

实现

_userRepository.Create(Mapper.Map<UserModel>(someUserViewModelWithRolesAttached);

最佳答案

Is this the most optimal way to do the mapping, or is AutoMapper capable of mapping Roles to Roles on its own?

如果属性名称相同,则不必手动提供映射:

Mapper.CreateMap<UserModel, UserViewModel>();
Mapper.CreateMap<UserViewModel, UserModel>();

只要确保内部类型也被映射(RoleViewModelRoleModel)

然而,这意味着如果您更改源或目标属性名称,AutoMapper 映射可能会悄无声息地失败并导致难以追踪问题(例如,如果您将 UserModel.Roles 更改为UserModel.RolesCollection 无需更改 UserViewModels.Roles)。

AutoMapper 提供了一个 Mapper.AssertConfigurationIsValid() 方法,该方法将检查所有映射是否有错误并捕获配置错误的映射。有一个与构建一起运行的单元测试非常有用,可以验证您对此类问题的映射。

关于c# - 具有相同属性名称的 AutoMapper 双向映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25536945/

相关文章:

c# - 自动映射器 : almost always trim strings

c# - 是否可以告诉自动映射器在运行时忽略映射?

c# - 使用 Unirest C# 将 http 响应主体转换为 JSON 格式

c# - 我该如何解决这个 "System.Data.Entity.DynamicProxies"错误

c# - 单元测试 DelegatingHandler

c# - 如何使用 AutoMapper 映射子对象?

c# - Automapper 有时无法映射通过 ForMember 设置的属性

c# - AutoMapper 更改类型

c# - 在 C# 中重命名 Excel 工作表名称

c# - ValueTypes 如何从 Object (ReferenceType) 派生并仍然是 ValueTypes?