2017-10-17 80 views
5

我有一個項目使用AutoMapper 3.1.1,我能夠隔離我遇到的問題。爲什麼意外映射在AutoMapper中發生?

這裏是我的測試類:

class BaseClass 
{ 
    public string PropertyA { get; set; } 
} 

class DerivedClass: BaseClass 
{ 
    public string PropertyB { get; set; } 
} 

class ContainerClass 
{ 
    public DerivedClass ComplexProperty { get; set; } 
    public string PropertyC { get; set; } 
} 

class SourceClass 
{ 
    public string PropertyA { get; set; } 
    public string PropertyB { get; set; } 
    public string PropertyC { get; set; } 
} 

這裏是我的映射規則:

Mapper.CreateMap<SourceClass, ContainerClass>() 
    .ForMember(d => d.ComplexProperty, o => o.MapFrom(s => Mapper.Map<DerivedClass>(s))) 
    .AfterMap((s, d) => System.Diagnostics.Debug.WriteLine("SourceClass-> ContainerClass mapped")); 

Mapper.CreateMap<SourceClass, DerivedClass>() 
    .AfterMap((s, d) => System.Diagnostics.Debug.WriteLine("SourceClass -> DerivedClass mapped")); 

Mapper.CreateMap<BaseClass, DerivedClass>() 
    .AfterMap((s, d) => System.Diagnostics.Debug.WriteLine("BaseClass -> DerivedClass mapped")); 

這是我的代碼:

var source = new SourceClass { 
    PropertyA = "ValueA", 
    PropertyB = "ValueB", 
    PropertyC = "ValueC", 
}; 

var destination = Mapper.Map<ContainerClass>(source); 

Console.WriteLine("PropertyA: " + destination?.ComplexProperty?.PropertyA); 
Console.WriteLine("PropertyB: " + destination?.ComplexProperty?.PropertyB); 
Console.WriteLine("PropertyC: " + destination?.PropertyC); 

的輸出是:

PropertyA: ValueA 
PropertyB: 
PropertyC: ValueC 

我期望PropertyB的值爲「ValueB」,但它的值爲null。它發生了,因爲從BaseClass到DerivedClass的映射器執行的原因是某種原因。我的調試輸出如下:

SourceClass -> DerivedClass mapped 
BaseClass -> DerivedClass mapped 
SourceClass -> ContainerClass mapped 

爲什麼AutoMapper執行BaseClass - > DerivedClass映射?


UPDATE: 謝謝馬呂斯現在我知道,從BaseClass的到DerivedClass該映射無效。他建議我不能刪除這個映射規則,因爲我需要它用於我的應用程序。作爲例外,建議我加忽略了PropertyB:

Mapper.CreateMap<BaseClass, DerivedClass>() 
    .ForMember(d => d.PropertyB, o => o.Ignore()) 
    .AfterMap((s, d) => System.Diagnostics.Debug.WriteLine("BaseClass -> DerivedClass mapped")); 

現在Mapper.AssertConfigurationIsValid();不會拋出異常了。但原來的問題依然存在。爲什麼AutoMapper執行BaseClass - > DerivedClass映射?

回答

1

調試時AutoMapper問題,我建議通過調用Mapper.AssertConfigurationIsValid();我把它添加到您的代碼來驗證配置和我得到了以下異常消息:

錯誤消息:AutoMapper.AutoMapperConfigurationException:發現未映射 成員。查看下面的類型和成員。添加自定義 映射表達式,忽略,添加自定義解析器或修改源/目標類型

======================== ==========

的BaseClass - > DerivedClass(目標成員列表)src.BaseClass - > src.DerivedClass (目標成員列表)

PropertyB

你可以通過去除BaseClass -> DerivedClass的映射來解決問題。然後還致電Mapper.AssertConfigurationIsValid();不再拋出。

+0

我更新了我的問題。我不能只刪除BaseClass - > DerivedClass,我需要它爲我的應用程序。 –