2012-02-03 73 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