自动映射器返回一个空集合,我想要一个空值
本文关键字:一个 集合 我想要 空值 空集 映射 返回 | 更新日期: 2023-09-27 18:34:02
public class Person
{
Name { get; set; }
IEnumerable<Address> Addresses { get; set; }
}
public class PersonModel
{
Name { get; set; }
IEnumerable<AddressModel> Addresses { get; set; }
}
如果我像这样将Person
映射到PersonModel
:
Mapper.DynamicMap<Person, PersonModel>(person);
如果Person
上的Addresses
属性为 null,则它们在PersonModel
上映射为空Enumerable
而不是 null。
如何让PersonModel
具有空Addresses
而不是空Enumerable
?
简单的答案是使用 AllowNullCollections
:
AutoMapper.Mapper.Initialize(cfg =>
{
cfg.AllowNullCollections = true;
});
或者如果您使用实例 API
new MapperConfiguration(cfg =>
{
cfg.AllowNullCollections = true;
}
除了在映射器配置初始化中设置AllowNullCollections
(如此答案中所述)之外,您还可以选择在Profile
定义中设置AllowNullCollections
,如下所示:
public class MyMapper : Profile
{
public MyMapper()
{
// Null collections will be mapped to null collections instead of empty collections.
AllowNullCollections = true;
CreateMap<MySource, MyDestination>();
}
}
因此,可能有几种方法可以使用自动映射器来实现此目的,这只是其中一种:
Mapper.CreateMap<Person, PersonMap>()
.AfterMap( (src, dest) => dest.Addresses = dest.Addresses?.Any() ? dest.Addresses : null );
此代码使用新的 c# ?.
运算符以确保 null 安全,因此,如果无法在代码中使用该功能,则可能需要删除该运算符并检查 null。
另一种替代方法是使用条件,因此仅在值不为 null 时才映射值。这可能需要值默认为 null(因为它不会被映射)
Mapper.CreateMap<Person, PersonModel>()
.ForMember(
dest => dest.Addresses,
opt => opt => opt.Condition(source=> source.Addresses!= null));
您应该能够为要对其执行此行为的属性定义自定义解析程序。 所以像这样:
Mapper.CreateMap<Address, AddressModel>();
Mapper.CreateMap<Person, PersonModel>()
.ForMember(
dest => dest.Addresses,
opt => opt.ResolveUsing(person => person.Addresses.Any() ? person.Addresses.Select(Mapper.Map<Address, AddressModel>) : null));
如果您希望将其作为 API 中的一般规则,则可以在配置服务方法中配置自动映射器,如下所示。
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers();
[...]
// configure automapping
services.AddAutoMapper(cfg => cfg.AllowNullCollections = true, typeof(Startup));
}
或者,在单独的 DLL 中使用自动映射的情况下(例如:对于 DTO 服务),我更喜欢使用帮助程序函数,因此配置也应该在那里完成:
public static class MappingHelper
{
private static readonly Lazy<IMapper> _lazy = new(() =>
{
var config = new MapperConfiguration(cfg =>
{
// This line ensures that internal properties are also mapped over.
cfg.ShouldMapProperty = p => p.GetMethod.IsPublic || p.GetMethod.IsAssembly;
cfg.AddProfile<DomainToRepositoryProfile>();
cfg.AddProfile<RepositoryToDomainProfile>();
cfg.AllowNullCollections = true;
});
var mapper = config.CreateMapper();
return mapper;
});
public static IMapper Mapper => _lazy.Value;
}
我无法使用 AutoMapper 12.0.1 和实体框架核心 6.0.15 脚手架实体让 AllowNullCollections 与 net6 一起工作。唯一有效的方法是:
internal class UserDtoMapper : Profile
{
public UserDtoMapper()
{
CreateMap<User, UserDto>()
.ForMember(dest => dest.Votes,
x => x.Condition(src => src.Votes != null && src.Votes.Any()))
.ReverseMap();
}
}
public partial class User
{
// ...
public virtual ICollection<Vote> Votes { get; set; }
}
public class UserDto
{
// ...
public List<VoteDto>? Votes { get; set; }
}