【发布时间】:2014-04-09 11:56:40
【问题描述】:
不确定这是一个错误还是我没有正确使用它,但似乎 Automapper 可以映射属性,即使 AssertConfigurationIsValid 失败。在以下测试中,即使AssertConfigurationIsValid 在ShouldValidateAgainstSourceListOnly 中失败,ShouldMapSourceList 也会通过:
using AutoMapper;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AutoMapperTests
{
[TestClass]
public class CreateMapTests
{
private class A
{
public string PropID { get; set; }
public string PropB { get; set; }
}
private class B
{
public string PropId { get; set; }
public string PropB { get; set; }
public string PropC { get; set; }
}
internal class CreateMapTestProfile : Profile
{
protected override void Configure()
{
// will complain about Unmapped member PropC when AssertConfigurationIsValid is called.
CreateMap<A, B>();
}
}
internal class CreateMapTestWithSourceMemberListProfile : Profile
{
protected override void Configure()
{
// will complain about Unmapped member PropID when AssertConfigurationIsValid is called.
CreateMap<A, B>(MemberList.Source);
}
}
[TestMethod]
public void ShouldMapSourceList()
{
Mapper.AddProfile<CreateMapTestWithSourceMemberListProfile>();
//Mapper.AssertConfigurationIsValid();
var a = new A
{
PropID = "someId",
PropB = "random",
};
var actual = Mapper.Map<B>(a);
Assert.AreEqual("someId", actual.PropId);
}
[TestMethod]
public void ShouldValidateAgainstSourceListOnly()
{
Mapper.AddProfile<CreateMapTestWithSourceMemberListProfile>();
Mapper.AssertConfigurationIsValid();
// if we got here without exceptions, it means we're good!
Assert.IsTrue(true);
}
}
}
如果配置无效,映射是否应该失败?或者如果配置有效,为什么AssertConfigurationIsValid会失败?
在这里测试项目:https://github.com/mrchief/AutoMapperTests/blob/master/CreateMapTests.cs
【问题讨论】:
-
什么是
MemberList.Source? -
您可以传递给
CreateMap的枚举之一。本质上,它告诉 Automapper 检查所有源成员是否已映射。默认为MemberList.Destination。 -
我对@987654331@ 的理解是它会检查目标类型上的缺失成员。这与根本无法映射这两种类型不同。 AutoMapper 仍会尝试在运行时尽可能地将类型相互映射。换句话说,仅仅因为
AssertConfigurationIsValid失败,并不意味着 AutoMapper 将无法映射类型。 -
@AndrewWhitaker:在这种情况下,不应该传递
MemberList.Source使其有效,因为所有源成员都已映射? -
@Mrchief:好吧,抱歉,我错过了那个细节。
MemberList.Source之前我并没有真正使用过。
标签: c# automapper