你什么时候收到错误?是不是当你拨打AssertConfigurationIsValid
?
如果是,则根本不调用此方法
你不必调用此方法,请考虑以下映射,其工作原理:
public class Foo1
{
public string Field1 { get; set; }
}
public class Foo2
{
public string Field1 { get; set; }
public string Field2 { get; set; }
}
Mapper.CreateMap<Foo1, Foo2>();
var foo1 = new Foo1() {Field1 = "field1"};
var foo2 = new Foo2();
Mapper.Map(foo1, foo2);//maps correctly, no Exception
您可能需要调用AssertConfigurationIsValid
为其他映射,以确保它们是正确的,所以你需要做的是组织你的映射到配置文件:
public class MyMappedClassesProfile: Profile
{
protected override void Configure()
{
CreateMap<Foo1, Foo2>();
//nb, make sure you call this.CreateMap and NOT Mapper.CreateMap
//I made this mistake when migrating 'static' mappings to a Profile.
}
}
Mapper.AddProfile<MyMappedClassesProfile>();
,然后如果你决定要检查映射(情况下,通过在您的情况逐一)的有效性,然后调用
Mapper.AssertConfigurationIsValid(typeof(MyMappedClassesProfile).FullName);
重要的,你的情况和/或任何情况下,你不要致电AssertConfigurationIsValid
你应该使用类似AutoFixture和单元测试来确保你的映射工作。 (这是AssertConfigurationIsValid
的意图)
来源
2012-11-13 12:59:31
wal
这是当我打电话AssertConfigurationIsValid,但我会perefered保持它在我的单元测试。现在它在Global.asax中,但最终会移动到单元测试中(这是一个ASP.NET MVC应用程序)。所以基本上你告诉我,我应该避免使用AssertConfigurationIsValid并为我的DAL编写我自己的单元测试? – Pluc
我不会告诉你在*每个* case中都会这样做......在映射非常简单的地方,然后继续使用AssertConfigurationIsValid。在它变得有问题的地方,因为你知道最好不要使用它。但是,您应该将映射组织到Profiles(扩展AutoMapper.Profile的类)中,以减少映射配置的静态性质和对AssertConfigurationIsValid的调用,然后这些调用将适用于每个Mapper.Map声明,做了。 – wal
由于我将EF POCO映射到DTO,因此每个实体都会丢失属性。 DTO永远不会包含其他的DTO,而是保留这些ID(一对一/多关系)或者调用负责请求实体(使用其ID作为参数)的适当库。有些只是一个缺少的财产,但他们都至少有一个。我不确定使用配置文件会带给我多少,因为映射只在Web服务器启动时配置一次(因为它是一个Web应用程序)。我也只使用AutoMapper for Model => DTO。除非我开始将它用于ViewModels,否则我没有看到需要。 – Pluc