你什麼時候收到錯誤?是不是當你撥打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