我最近給Automapper一個鏡頭,一旦我得到它的工作,它絕對是太棒了。問題是,我必須編寫的實際代碼來設置Automapper是非常糟糕的,我想知道我正在做這件事的方式是否可以改進或簡化。我正在使用它(在以下示例中)將我的實體轉換爲視圖模型。字段名稱是完全不同的,所以我必須在Global.asax
手動創建的映射(據我所知)最有效的方法來編寫AutoMapper代碼?
public static class AutoMapperConfig
{
public static void RegisterMappings()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<customer_master, CustomerViewModel>()
.ForMember
(dst => dst.FirstName, src => src.MapFrom(e => e.cm_firstname))
.ForMember
(dst => dst.LastName, src => src.MapFrom(e => e.cm_lastname))
.ForMember
(dst => dst.Id, src => src.MapFrom(e => e.cm_id))
.ForMember
(dst => dst.Address1, src => src.MapFrom(e => e.cm_address1))
.ForMember
(dst => dst.Address2, src => src.MapFrom(e => e.cm_address2))
.ForMember
(dst => dst.City, src => src.MapFrom(e => e.cm_city))
.ForMember
(dst => dst.State, src => src.MapFrom(e => e.cm_state))
.ForMember
(dst => dst.Zip, src => src.MapFrom(e => e.cm_zip))
.ForMember
(dst => dst.Country, src => src.MapFrom(e => e.cm_country))
.ForMember
(dst => dst.Email, src => src.MapFrom(e => e.cm_email))
.ForMember
(dst => dst.Phone, src => src.MapFrom(e => e.cm_phone))
.ForMember
(dst => dst.Fax, src => src.MapFrom(e => e.cm_fax))
.ForMember
(dst => dst.Active, src => src.MapFrom(e => e.cm_active))
.ForMember
(dst => dst.Company, src => src.MapFrom(e => e.cm_company));
cfg.CreateMap<CustomerViewModel, customer_master>()
.ForMember
(dst => dst.cm_firstname, src => src.MapFrom(e => e.FirstName))
.ForMember
(dst => dst.cm_lastname, src => src.MapFrom(e => e.LastName))
.ForMember
(dst => dst.cm_id, src => src.MapFrom(e => e.Id))
.ForMember
(dst => dst.cm_address1, src => src.MapFrom(e => e.Address1))
.ForMember
(dst => dst.cm_address2, src => src.MapFrom(e => e.Address2))
.ForMember
(dst => dst.cm_city, src => src.MapFrom(e => e.City))
.ForMember
(dst => dst.cm_state, src => src.MapFrom(e => e.State))
.ForMember
(dst => dst.cm_zip, src => src.MapFrom(e => e.Zip))
.ForMember
(dst => dst.cm_country, src => src.MapFrom(e => e.Country))
.ForMember
(dst => dst.cm_email, src => src.MapFrom(e => e.Email))
.ForMember
(dst => dst.cm_phone, src => src.MapFrom(e => e.Phone))
.ForMember
(dst => dst.cm_fax, src => src.MapFrom(e => e.Fax))
.ForMember
(dst => dst.cm_active, src => src.MapFrom(e => e.Active))
.ForMember
(dst => dst.cm_company, src => src.MapFrom(e => e.Company));
});
}
}
然後:
AutoMapperConfig.RegisterMappings();
晴我的問題是:
- 做場名稱必須像這樣明確地映射,因爲名稱是如此不同?
- 有沒有辦法只寫第一個地圖,然後將其用於第二呢?實體 - > ViewModel與ViewModel - > Entity相同,這樣寫兩次似乎是多餘的。我想我在這裏尋找某種雙向選項。
感謝這個,我的實體設計不** ** EXACLTY遵循此基礎上,表名「CM_」的變化,有可能是在屬性名(「FIRST_NAME」來說吧)下劃線,但這是向正確的方向 – Halter
了巨大的一步,應該是沒有問題的,因爲你可以添加很多的前綴(這是字符串數組)。下劃線也可以處理。 – Evk