2012-02-03 70 views
1

考慮下面的實體模型:爲什麼在這裏需要自定義解析器(AutoMapper)?

public class Location 
{ 
    public int Id { get; set; } 
    public Coordinates Center { get; set; } 
} 
public class Coordinates 
{ 
    public double? Latitude { get; set; } 
    public double? Longitude { get; set; } 
} 

...及以下視圖模型:

public class LocationModel 
{ 
    public int Id { get; set; } 
    public double? CenterLatitude { get; set; } 
    public double? CenterLongitude { get; set; } 
} 

的LocationModel屬性命名,使得從實體映射到模型不需要定製解析器。

但是從模型映射到實體時,需要以下自定義解析:

CreateMap<LocationModel, Location>() 
    .ForMember(target => target.Center, opt => opt 
     .ResolveUsing(source => new Coordinates 
      { 
       Latitude = source.CenterLatitude, 
       Longitude = source.CenterLongitude 
      })) 

這是爲什麼?有沒有更簡單的方法讓AutoMapper根據viewmodel中的命名約定構造一個新的座標值對象?

更新

要回答第一個評論,並沒有什麼特別之處實體視圖模型映射:

CreateMap<Location, LocationModel>(); 
+0

您可以包括從實體模型的映射? – 2012-02-03 17:31:38

+0

我已經包含了從實體到模型的映射。 – danludwig 2012-02-03 19:01:25

回答

1

編輯

請參閱下面的評論線程。這個答案實際上是相反的映射。


你在做別的事情。您正確地遵守了約定,因此映射應該無需解析器即可工作。

我只是嘗試這樣做測試,並且它通過了:

public class Location 
{ 
    public int Id { get; set; } 
    public Coordinates Center { get; set; } 
} 

public class Coordinates 
{ 
    public double? Latitude { get; set; } 
    public double? Longitude { get; set; } 
} 

public class LocationModel 
{ 
    public int Id { get; set; } 
    public double? CenterLatitude { get; set; } 
    public double? CenterLongitude { get; set; } 
} 

[Test] 
public void LocationMapsToLocationModel() 
{ 
    Mapper.CreateMap<Location, LocationModel>(); 

    var location = new Location 
    { 
     Id = 1, 
     Center = new Coordinates { Latitude = 1.11, Longitude = 2.22 } 
    }; 

    var locationModel = Mapper.Map<LocationModel>(location); 

    Assert.AreEqual(2.22, locationModel.CenterLongitude); 
} 
+0

是的。從實體到視圖模型的映射工作得很好。這是我發現需要解析器的另一種方式:Mapper.CreateMap ()'。 – danludwig 2012-02-03 18:59:57

+0

@ olivehour,抱歉抱歉。在那種情況下,是的,我認爲你確實需要一個自定義解析器。據我所知,AutoMapper不會「解凍」,只是扁平化。你可能想看看ValueInjecter(注意拼寫)。 – devuxer 2012-02-03 19:10:27

+0

謝謝,以前從來沒有聽說過那個lib。 – danludwig 2012-02-03 19:34:20