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; }
}

LocationModelプロパティは、エンティティからモデルへのマッピングがカスタムリゾルバーを必要としないように名前が付けられています。

ただし、モデルからエンティティにマッピングする場合は、次のカスタムリゾルバーが必要です。

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

どうしてこれなの?AutoMapperを作成して、ビューモデルの命名規則に基づいて新しいCoordinates値オブジェクトを作成する簡単な方法はありますか?

アップデート

最初のコメントに答えるために、ビューモデルマッピングへのエンティティについて特別なことは何もありません。

CreateMap<Location, LocationModel>();
4

1 に答える 1

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);
}
于 2012-02-03T18:08:08.230 に答える