2016-03-03 186 views
4

在MVC應用程序中做同樣的實體類型的副本,但是希望忽略複製主鍵(對現有實體進行更新)。但在下面的地圖中將Id列設置爲忽略不起作用,並且Id被覆蓋。AutoMapper ForMember忽略不工作

cfg.CreateMap<VendorContact, VendorContact>() 
    .ForMember(dest => dest.Id, option => option.Ignore()) 
    .ForMember(dest => dest.CreatedById, option => option.Ignore()) 
    .ForMember(dest => dest.CreatedOn, option => option.Ignore()) 
    ; 

執行映射:

existingStratusVendorContact = Mapper.Map<VendorContact>(vendorContact); 

this other answer,但現在看來,我這樣做了。

UPDATE:

據透露,我創造我的地圖在Global.asax像這樣:

Mapper.Initialize(cfg => 
{ 
    cfg.CreateMap<VendorContact, VendorContact>() 
     .ForMember(dest => dest.Id, option => option.Ignore()) 
     .ForMember(dest => dest.CreatedById, option => option.Ignore()) 
     .ForMember(dest => dest.CreatedOn, option => option.Ignore()) 
     ; 

}); 
+0

'existingStratusVendorContact'是一個現有的對象,你想替換除'Id','CreatedById','CreatedOn'之外的屬性嗎?或者用這個屬性的默認值創建一個新的? –

+0

是的,前者。更新除這3個屬性以外的現有對象。 –

回答

2

你的問題是你沒有給automapper現有的對象。 Automapper絕對可以做到這一點。

Mapper.Map<VendorContact>(vendorContact, existingStratusVendorContact); 

應該做你想做的。您目前的代碼正在創建一個全新的對象,並用全新的對象替換existingStratusVendorContact。如您所料,上述代碼將採用現有的對象和更新值。

+0

謝謝。這似乎是工作,但後來我試圖保存existingStratusVendorContact時出現錯誤。 '操作失敗:'該關係無法更改,因爲一個或多個外鍵屬性不可空。當對關係進行更改時,相關的外鍵屬性將設置爲空值。 ...'當我在保存時查看該實體時,它看起來像所有的外鍵都在調試器中填充...所以不知道發生了什麼。關於實體框架如何處理我想的東西。 –

+0

知道了!我的最後一個問題是我如何檢索要更新的實體。當我改變它以獲得它.AsNoTracking ...然後它工作。 –

0

UPDATE:

問題是,當你分配給Mapper.Map<VendorContact>(vendorContact);existingStratusVendorContact正在用Map()方法替換變量的當前值,而不管你忽略了哪些屬性。

With Mapper.Map(source)根據一些慣例,您可以將對象投影到其他類型複製屬性的新對象,但是您正在創建一個新對象。

在您的代碼中,您正在使用其默認值創建具有Id,CreatedByIdCreatedOn屬性的新對象。

您可以使用Mapper.Map(source, destination)重載,不正是你想要什麼:

Mapper.Map<VendorContact>(vendorContact, existingStratusVendorContact); 

ORIGINAL:

如果您要創建這樣您的地圖:

var cfg = new MapperConfiguration(c => 
{ 
    c.CreateMap<VendorContact, VendorContact>() 
     .ForMember(dest => dest.Id, option => option.Ignore()) 
     .ForMember(dest => dest.CreatedById, option => option.Ignore()) 
     .ForMember(dest => dest.CreatedOn, option => option.Ignore()); 
}); 

您需要使用此配置創建映射器:

var mapper = cfg.CreateMapper(); 

,並使用它的對象映射:

var existingStratusVendorContact = mapper.Map<VendorContact>(vendorContact); 

如果使用靜態類Mapper默認行爲是用來和屬性映射。

+0

@ArturoMechaca謝謝阿圖羅。看到我更新的問題,指出我如何創建地圖。這是如何影響你的答案的?另外,這就是我在使用AutoMapper 3的解決方案中的另一個項目中所做的工作。但是,此新項目使用的是AutoMapper 4.所以,可能會更改首選Map創建方法/語法? –

+0

@ArturoMechaca這是錯誤的,請參閱https://github.com/AutoMapper/AutoMapper/blob/develop/src/AutoMapper/Mapper.cs#L140'映射的目標對象,與 object' –

+0

@ChadRichardson:找到一種方法可以用Automapper來完成。感謝Tomas –