Skip to content

Instantly share code, notes, and snippets.

@ichiroku11
Last active October 23, 2018 03:00
Show Gist options
  • Save ichiroku11/faede55840c337919b3eb4845a125450 to your computer and use it in GitHub Desktop.
Save ichiroku11/faede55840c337919b3eb4845a125450 to your computer and use it in GitHub Desktop.
AutoMapper - 継承したオブジェクトをマッピングする
using System;
using AutoMapper;
namespace ConsoleApp {
// コピー元の親クラス
public abstract class SampleSrcBase {
public int Id { get; set; }
public string Value1 { get; set; }
}
// コピー元
public class SampleSrc : SampleSrcBase {
public string Value2 { get; set; }
}
// コピー先
public class SampleDst {
public int Id { get; set; }
public string Value1 { get; set; }
public string Value2 { get; set; }
}
// マッピングのプロファイル
public class SampleProfile : Profile {
public SampleProfile() {
CreateMap<SampleSrc, SampleDst>();
}
}
class Program {
static void Main(string[] args) {
// マッピングを用意
Mapper.Initialize(config => {
config.AddProfile<SampleProfile>();
});
Mapper.AssertConfigurationIsValid();
SampleSrcBase getSrc() => new SampleSrc {
Id = 1,
Value1 = "x",
Value2 = "y",
};
// srcはSampleSrcBase
var src = getSrc();
// マップ
var dst = Mapper.Map<SampleDst>(src);
// 確認
// Value2もマッピングされている
Console.WriteLine(dst.Id); // 1
Console.WriteLine(dst.Value1); // x
Console.WriteLine(dst.Value2); // y
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment