![](/img/trans.png)
[英]AutoMapper: Set all properties of destination object to default if source object is null for specified types
[英]Automapper If source is null, set destination object properties
我有以下情况:
资料来源 :
public class AccountLogin
{
public int UserID { get; set; }
public bool AccountVerified { get; set; }
}
该对象是从数据库返回的,因此如果找不到用户,则该对象可能为null
目的地 :
public class LoginUserResponseModel
{
public bool AccountExists { get; set; }
public bool AccountVerified { get; set; }
public string Status { get; set; }
public string Token { get; set; }
}
我需要什么?
如果源为null,则需要具有以下参数的目标对象的实例:
{
"AccountExists": false,
"AccountVerified": false
"Status": "Error"
"Token": null
}
我放入MappingProfile.cs
文件中的AutoMapper
代码如下:
CreateMap<AccountLogin, LoginUserResponseModel>()
.ForMember(dest => dest.AccountExists, opt => opt.MapFrom(src => src == null ? false : true))
.ForMember(dest => dest.Status, opt => opt.MapFrom(src => src == null ? "Error" : "Ok"));
当对象不为null时,此代码可以正常工作,它设置Status = "Ok"
且AccountExists = false
当我从数据库接收到现有用户时,我的源AccountLogin
,例如:
问题是当源为空时,目标也为空:
我有很多解决方法,但是我真的很好奇是否可以使用AutoMapper
。
我正在使用的项目是ASP Net Core 2.2
和AutoMapper v6.1.1
为了回应您的意见,我建议使用CustomTypeConverter: http ://docs.automapper.org/en/stable/Custom-type-converters.html
public class AccountLoginConverter : ITypeConverter<AccountLogin, LoginUserResponseModel>
{
public LoginUserResponseModel Convert(AccountLogin source, LoginUserResponseModel destination, ResolutionContext context)
{
if(source == null)
{
return new LoginUserResponseModel { AccountExists = false, Status = "Error" }
}
// You can have more complex logic here
return new LoginUserResponseModel
{
AccountExists = true,
AccountVerified = true, // Or more logic
Status = "Ok"
};
}
}
为了设置新设计的转换器:
cfg.CreateMap<AccountLogin, LoginUserResponseModel>().ConvertUsing(new AccountLoginConverter());
要么
cfg.CreateMap<AccountLogin, LoginUserResponseModel>().ConvertUsing<AccountLoginConverter>();
您可以尝试使用自定义ITypeConverter进行ConvertUsing:
public class MyConverter : ITypeConverter<AccountLogin, LoginUserResponseModel >
{
public int Convert(AccountLogin source, LoginUserResponseModel destination, ResolutionContext context)
{
return new LoginUserResponseModel{
AccountExists = source == null ? false : true,
AccountVerified = false,
Status = source == null ? "Error" : "Ok",
"Token": null
};
}
}
然后用:
CreateMap<AccountLogin, LoginUserResponseModel>().ConvertUsing(new MyConverter());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.