2016-06-08 39 views
3

下面給出下面的代碼,爲什麼我在映射階段不斷收到異常?這兩個DTO真的不一樣嗎?以下是引發異常的符號服務器pdb中的代碼行。爲什麼AutoMapper配置不能正確映射?

throw new AutoMapperMappingException(context, "Missing type map configuration or unsupported mapping."); 

什麼是真是笑死我了是,@jbogard做的異常處理和儀器儀表與問候AutoMapper一個殺手的工作,有大量的源和目標對象的上下文數據,以及映射器的狀態當一個異常拋出..我仍然無法弄清楚。

void Main() 
{ 
    var config = new MapperConfiguration(cfg => 
    { 
     cfg.ShouldMapProperty = p => p.GetMethod.IsPublic || p.GetMethod.IsVirtual; 
     cfg.CreateMap<Customer, Customer2>() 
     .ReverseMap(); 
    }); 

    config.AssertConfigurationIsValid(); 

    Customer request = new Customer 
    { 
     FirstName = "Hello", LastName = "World" 
    }; 
    request.FullName = request.FirstName + " " + request.LastName; 

    Customer2 entity = Mapper.Map<Customer, Customer2>(request); 


    Console.WriteLine("finished"); 
} 



public class Customer 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public string FullName { get; set; } 
} 

[Serializable()] 
public partial class Customer2 
{ 
    private string _firstName; 
    private string _lastName; 
    private string _fullName; 

    public virtual string FirstName 
    { 
     get 
     { 
      return this._firstName; 
     } 
     set 
     { 
      this._firstName = value; 
     } 
    } 
    public virtual string LastName 
    { 
     get 
     { 
      return this._lastName; 
     } 
     set 
     { 
      this._lastName = value; 
     } 
    } 
    public virtual string FullName 
    { 
     get 
     { 
      return this._fullName; 
     } 
     set 
     { 
      this._fullName = value; 
     } 
    } 
} 

謝謝 斯蒂芬

+0

什麼是提出異常的細節? – lzcd

+0

'Customer2'被標記爲「partial」,其餘的課程在哪裏? –

回答

8

拉動來源並添加AutoMapper.Net4項目到控制檯我能診斷問題之後。

當Jimmy刪除靜態版本,然後通過我重新添加它以防止它重新添加它時,引入的API現在與新API的語法稍微有點不同,反正。以下是添加源代碼時的例外情況,請注意這與通過Nuget最初拋出的內容有何區別?

throw new InvalidOperationException("Mapper not initialized. Call Initialize with appropriate configuration."); 

這使我馬上回GitHub上,在那裏Getting Started Docs我很快發現,我沒有初始化,像這樣

var mapper = config.CreateMapper(); 

映射器然後,而不是靜態映射

Cutomer2 entity = Mapper.Map<Customer, Cutomer2>(request); 

使用IMapper接口上面,像這樣

Cutomer2 entity = mapper.Map<Customer, Cutomer2>(request); 

問題解決。希望這有幫助

+2

如果您想使用靜態映射器類,也可以使用Mapper.Initialize。 –

相關問題