我使用Automapper将具有null集合的类映射到具有相同集合的目标。我需要目标集合也为空。
Profile类中有一个名为AllowNullCollections的属性。它不会影响映射。 如果我将cfg.AllowNullCollections设置为True,映射会将目标集合保留为null(我想要)。
对于系统中的所有映射,我无法将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; }
}
}
答案 0 :(得分:0)
你可以用下面的方法替换TestMappingProfile Ctor,它应该可以工作:
public TestMappingProfile() {
CreateMap()。ForMember(dest =&gt; dest.Ints,opt =&gt; opt.Condition(src =&gt;(src.Ints!= null)));
}
答案 1 :(得分:0)
Ray会在github上提交一个问题。当前状态是您无法在利润级别设置AllowNullCollections,您必须将其设置为配置级别。