使用AutoMapper映射时将IsActive布尔属性设为false的实现方案
解决AutoMapper在DeactivateUser方法中的两个需求
1. 映射时自动将IsActive设为false
在AutoMapper的Profile配置中,直接通过ForMember指定IsActive的固定值即可,无需手动给Dto赋值:
public class UserProfile : Profile { public UserProfile() { CreateMap<User, IsActiveDto>() .ForMember(dest => dest.IsActive, opt => opt.Value(false)); } }
当你执行mapper.Map<IsActiveDto>(user)时,IsActive属性会被自动设置为false。如果后续需要基于源对象逻辑调整(当前需求为固定false),也可以用MapFrom实现:
.ForMember(dest => dest.IsActive, opt => opt.MapFrom(src => false));
2. 用ConstructUsing创建IsActiveDto实例(遵循单一职责)
BeforeMap的设计定位是映射前后的额外操作,并不适合负责目标对象的实例化。AutoMapper提供ConstructUsing方法专门控制目标对象的创建,这样能将实例化逻辑与属性映射逻辑分离,符合单一职责原则。
基础实例创建
public class UserProfile : Profile { public UserProfile() { CreateMap<User, IsActiveDto>() .ConstructUsing(src => new IsActiveDto()) // 自定义实例创建逻辑 .ForMember(dest => dest.IsActive, opt => opt.Value(false)); } }
带依赖的实例创建
如果IsActiveDto的实例化需要依赖其他服务(比如ASP.NET Core依赖注入场景),可以通过Profile构造函数注入依赖后在ConstructUsing中使用:
public class UserProfile : Profile { private readonly IMyDependency _myDependency; public UserProfile(IMyDependency myDependency) { _myDependency = myDependency; CreateMap<User, IsActiveDto>() .ConstructUsing(src => new IsActiveDto(_myDependency.GetRequiredData())) .ForMember(dest => dest.IsActive, opt => opt.Value(false)); } }
这样,实例化逻辑由ConstructUsing负责,属性映射由ForMember负责,各自职责清晰,符合单一职责原则。
内容的提问来源于stack exchange,提问作者Onat Ege Karaman
相关产品推荐
相关产品推荐

