Automapper:在配置文件上设置AllowNullCollections
本文关键字:设置 AllowNullCollections 配置文件 Automapper | 更新日期: 2023-09-27 18:02:43
我使用Automapper将具有空集合的类映射到具有相同集合的目标。我需要目标集合也为空。
在Profile类中有一个属性叫做AllowNullCollections。它不会影响映射。如果我设置cfg。AllowNullCollections为True映射确实使目标集合为空(如我所愿)。我不能设置AllowNullCollections为True在我的系统中的所有映射,它必须只适用于我的配置文件。
using System.Collections.Generic;
using AutoMapper;
using NUnit.Framework;
using Assert = NUnit.Framework.Assert;
namespace Radfords.FreshCool.Web.Tests
{
[TestFixture]
[Category("UnitTest")]
class AutomapperTests
{
private IMapper _mapper;
// this says that AllowNullCollections does work at the profile level, in May.
//https://github.com/AutoMapper/AutoMapper/issues/1264
[SetUp]
public void SetUp()
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile<TestMappingProfile>();
// I want the profile to set the configuration, if I set this here the test passes
//cfg.AllowNullCollections = true;
});
_mapper = config.CreateMapper();
}
[Test]
[Category("UnitTest")]
public void MapCollectionsTest_MustBeNull()
{
var actual = _mapper.Map<Destination>(new Source());
Assert.IsNull(actual.Ints, "Ints must be null.");
}
}
internal class TestMappingProfile : Profile
{
public TestMappingProfile()
{
AllowNullCollections = true;
CreateMap<Source, Destination>();
}
}
internal class Source
{
public IEnumerable<int> Ints { get; set; }
}
internal class Destination
{
public IEnumerable<int> Ints { get; set; }
}
}
Will Ray在github上提交了一个issue。当前的状态是你不能在利润级别设置AllowNullCollections,你必须在配置级别设置它。
你可以用下面的代码替换TestMappingProfile函数,它应该可以工作:
public TestMappingProfile()
{
CreateMap<Source, Destination>().ForMember(dest => dest.Ints, opt => opt.Condition(src => (src.Ints != null)));
}