2011-10-28 21 views
1

我有需要映射到1種類的多個類:Automapper弄平使用createmap

這是我從(視圖模型)映射的源:

public class UserBM 
{ 
    public int UserId { get; set; } 

    public string Address { get; set; } 
    public string Address2 { get; set; } 
    public string Address3 { get; set; } 
    public string State { get; set; } 

    public int CountryId { get; set; } 
    public string Country { get; set; } 
} 

這是怎樣的目的地類(域模型):

public abstract class User 
{ 
    public int UserId { get; set; } 

    public virtual Location Location { get; set; } 
    public virtual int? LocationId { get; set; } 
} 

public class Location 
{ 
    public int LocationId { get; set; } 

    public string Address { get; set; } 
    public string Address2 { get; set; } 
    public string Address3 { get; set; } 
    public string State { get; set; } 

    public virtual int CountryId { get; set; } 
    public virtual Country Country { get; set; } 

} 

這是我automapper如何創建地圖目前的樣子:

Mapper.CreateMap<UserBM, User>(); 

根據對automapper的CodePlex網站上的文件,這應該是自動的,但它不工作。 Address,Address2等仍爲空。我的createmap應該是什麼樣子?

回答

0

的原因是因爲AutoMapper不能所有這些平板字段映射通過約定轉換爲Location對象。

你需要自定義解析。

Mapper.CreateMap<UserBM, User>() 
    .ForMember(dest => dest.Location, opt => opt.ResolveUsing<LocationResolver>()); 

public class LocationResolver : ValueResolver<UserBM,Location> 
{ 
    protected override Location ResolveCore(UserBMsource) 
    { 
     // construct your object here. 
    } 
} 

然而我不喜歡這個。海事組織,更好的辦法是在你的ViewModel這些屬性封裝到一個嵌套的視圖模型:

public class UserBM 
{ 
    public int UserId { get; set; } 
    public LocationViewModel Location { get; set; } 
} 

然後,所有你需要做的就是定義一個額外的地圖:

Mapper.CreateMap<User, UserBM>(); 
Mapper.CreateMap<LocationViewModel,Location>(); 

那麼它將所有的工作。

你應該嘗試使用AutoMapper約定,在可能的情況。當然可以讓你的ViewModel更加層次化,以匹配目的地層次。

0

編輯奇怪這個問題已經被問的你..似乎是一個同樣的問題 - 我想我失去了一些東西......

入住這SQ Question

*

定義兩個映射,從相同的源到不同的映射 目的地

*

+0

不同的問題,這是另一回事。 –

+0

雖然有相同的代碼,但它不會將2個對象映射到1 –

0

我想你需要做類似的屬性名稱LocationAddressLocationAddress2UserBM爲他們自動投影工作,但我可能是錯的。

看看他們的網頁上Flattening他們有級聯像我指示的源的兩種屬性名的屬性名。

0

只需按照你的目標類的命名約定,並與Location前綴地址屬性,因爲這是屬性名的源類:

public class UserBM 
{ 
    public int UserId { get; set; } 

    public string LocationAddress { get; set; } 
    public string LocationAddress2 { get; set; } 
    public string LocationAddress3 { get; set; } 
    public string LocationState { get; set; } 

    public int CountryId { get; set; } 
    public string Country { get; set; } 
} 
+0

我完全按照你所說的做了。除了將CountryId的位置置於前面之外。嘗試映射後,仍然user.Location爲空。 –

+0

@Lolcoder,你在說什麼'user.Location'?我認爲你的源類型是'User',你的目標類型是'UserBM'('Mapper.CreateMap ();')。不是嗎?在這種情況下,你將擁有'userBM.LocationAddress',... –