Created
October 18, 2018 08:32
-
-
Save ichiroku11/2e14e29397c1052473853e4d80c7f30f to your computer and use it in GitHub Desktop.
AutoMapper - コンストラクタを呼び出してマッピング
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using AutoMapper; | |
namespace ConsoleApp { | |
// 参考 | |
// http://docs.automapper.org/en/stable/Construction.html | |
// コピー元 | |
public class SampleSrc { | |
public int Id { get; set; } | |
public string Value { get; set; } | |
} | |
// コピー先 | |
public class SampleDst { | |
public SampleDst(int id, string value) { | |
// SampleDst constructor(1, x) | |
Console.WriteLine($"{nameof(SampleDst)} constructor({id}, {value})"); | |
Id = id; | |
Value = value; | |
} | |
public int Id { get; } | |
public string Value { get; } | |
} | |
// マッピングのプロファイル | |
public class SampleProfile : Profile { | |
public SampleProfile() { | |
CreateMap<SampleSrc, SampleDst>(); | |
} | |
} | |
class Program { | |
static void Main(string[] args) { | |
// マッピングを用意 | |
Mapper.Initialize(config => { | |
config.AddProfile<SampleProfile>(); | |
}); | |
Mapper.AssertConfigurationIsValid(); | |
var src = new SampleSrc { | |
Id = 1, | |
Value = "x", | |
}; | |
// src => dstにマップ | |
var dst = Mapper.Map<SampleDst>(src); | |
// 確認 | |
Console.WriteLine(dst.Id); // 1 | |
Console.WriteLine(dst.Value); // x | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment