2017-10-18 100 views
2

我在使用AutoMapper從數據傳輸對象映射到數據庫實體模型時遇到了一些麻煩。該實體具有幾個屬性,這些屬性是從IEnumerable派生的自定義數組類型。這些屬性沒有安裝程序,但有一種名爲SetFromString()的方法可用。我似乎無法正確配置我的地圖來使用它。 AutoMapper是否支持這種事情?如果有人能指出我的方向正確,我會很感激。AutoMapper - 使用方法來更新IEnumerable屬性沒有setter?

下面是我正在使用的關鍵類的簡化版本。 (映射工作得很好,從實體到DTO去,但我需要它在相反方向上正常工作。)

// The database entity 
public class ContactEntity 
{ 
    public CustomArray<String> CustomerNumbers { get; } 
} 

// The data transfer object 
public class ContactDto 
{ 
    public List<String> CustomerNumbers { get; set; } 
} 

// CustomArray definition 
public abstract class CustomArray<DataType> : IEnumerable<DataType>, IDisposable 
{ 
    protected CustomArray(); 
    public abstract void SetFromString(string Value); 
} 

我的映射分佈仍然是相當香草,因爲我不能環繞我的頭正確的ForMember語法。

public class ContactMappingProfile : Profile 
{ 
    public ContactMappingProfile() 
    { 
     // This map works fine 
     CreateMap<ContactEntity, ContactDto>(); 

     // Map from DTO to Entity    
     CreateMap<ContactDto, ContactEntity>() 
      .ForMember(dest => dest.CustomerNumbers, 
       opt => opt.ResolveUsing(src => src.CustomerNumbers)); 
    } 
} 

再次感謝您提供的任何幫助!

+0

如果你是做手工,你會如何轉換列表''到'字符串Value' 'SetFromString'方法需要嗎? –

+0

爲了簡單起見,假設字符串需要用逗號分隔。爲此,我的代碼看起來像這樣:'string.Join(「,」,src.CustomerNumbers);'。我遺漏的部分是如何將該值傳遞給'dest.CustomerNumbers.SetFromString();' – wags

回答

3

你可以使用任何UseDestinationValueIgnore爲目標實體CustomerNumbers成員和執行AfterMap實際映射:

cfg.CreateMap<ContactDto, ContactEntity>() 
    .ForMember(dest => dest.CustomerNumbers, opt => opt.Ignore()) 
    .AfterMap((src, dest) => dest.CustomerNumbers.SetFromString(string.Join(",", src.CustomerNumbers)));