Skip to content

Instantly share code, notes, and snippets.

@ichiroku11
Created October 18, 2018 08:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ichiroku11/2e14e29397c1052473853e4d80c7f30f to your computer and use it in GitHub Desktop.
Save ichiroku11/2e14e29397c1052473853e4d80c7f30f to your computer and use it in GitHub Desktop.
AutoMapper - コンストラクタを呼び出してマッピング
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