2013-10-30 200 views
3

我想從一個對象映射到另一個公共只讀Guid Id,我想忽略它。我曾嘗試這樣的:Automapper忽略只讀屬性

Mapper.CreateMap<SearchQuery, GetPersonsQuery>() 
       .ForMember(dto => dto.Id, opt => opt.Ignore()); 

這似乎失敗,因爲Id爲只讀:

AutoMapperTests.IsValidConfiguration threw exception: 
System.ArgumentException: Expression must be writeable 

有沒有解決這個辦法嗎?

+0

[Automapper和不變性(可能重複http://stackoverflow.com/questions/2195700/automapper -and-不變性) – rivarolle

回答

1

我不認爲ReadOnly字段是由AutoMapper支持的。只有這樣我能得到它的工作是與屬性包裹只讀字段只有一個getter:

class Program 
{ 
    static void Main() 
    { 
     Mapper.CreateMap<SearchQuery, GetPersonsQuery>(); 

     var source = new SearchQuery {Id = Guid.NewGuid(), Text = Guid.NewGuid().ToString() }; 

     Console.WriteLine("Src: id = {0} text = {1}", source.Id, source.Text); 

     var target = Mapper.Map<SearchQuery, GetPersonsQuery>(source); 

     Console.WriteLine("Tgt: id = {0} text = {1}", target.Id, target.Text); 

     Console.ReadLine(); 
    } 
} 

internal class GetPersonsQuery 
{ 
    private readonly Guid _id = new Guid("11111111-97b9-4db4-920d-2c41da24eb71"); 

    public Guid Id { get { return _id; } } 
    public string Text { get; set; } 
} 

internal class SearchQuery 
{ 
    public Guid Id { get; set; } 
    public string Text { get; set; } 
}