プロパティを再度初期化するためにオブジェクトを作成する必要はありません。AutoMapper を使用します。例
アドレス クラスの作成
public class Address
{
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
}
顧客クラスの作成
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public Address HomeAddress { get; set; }
public string GetFullName()
{
return string.Format("{0} {1}", FirstName, LastName);
}
}
コントローラーで、アクション メソッドを作成する
アプローチ - 1 (マッピングが作成されていない場合)
public class AutoMapperController : Controller
{
public ActionResult Index()
{
List<Customer> customers = new List<Customer>();
customers.Add(
new Customer
{
Email = "a@s.com",
FirstName = "F1",
LastName = "L1",
HomeAddress = new Address
{
Address1 = "A1",
Address2 = "A2",
City = "C1",
Country = "Co1",
PostalCode = "P1"
}
});
AutoMapper.Mapper.CreateMap<Customer, CustomerListViewModel>();
IList<CustomerListViewModel> viewModelList =
AutoMapper.Mapper.Map<IList<Customer>,
IList<CustomerListViewModel>>(customers);
return View(viewModelList);
}
}
さて、以下の結果が表示されたら... Customer クラスにデータがあり、AutoMapping を実行した後、CustomerListViewModel クラスに値が入力されます..
アプローチ - 2 マッピングが作成される場合
MyMappings というクラスを作成し、以下のコードを使用してマッピングを定義します。
public class MyMappings : Profile
{
public const string NameOfProfile = "ContactDataProfile";
public override string ProfileName
{
get
{
return NameOfProfile;
}
}
protected override void Configure()
{
CreateMaps();
}
private static void CreateMaps()
{
Mapper.CreateMap<Customer, CustomerListViewModel>()
.ForMember(dest => dest.Email, opt => opt.MapFrom(src => src.Email))
.ForMember(dest => dest.FullName, opt => opt.MapFrom(src => src.FirstName + "." + src.LastName))
.ForMember(dest => dest.HomeAddressCountry, opt => opt.MapFrom(src => src.HomeAddress))
.IgnoreAllNonExisting();
Mapper.AssertConfigurationIsValid();
}
}
以下は、いくつかのクラス プロパティ間のマッピングを出荷する場合に必要なクラスです。
public static class AutoMapperExtensions
{
public static IMappingExpression<TSource, TDestination>
IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
var sourceType = typeof(TSource);
var destinationType = typeof(TDestination);
var existingMaps = Mapper.GetAllTypeMaps().First(x => x.SourceType == sourceType && x.DestinationType == destinationType);
foreach (var property in existingMaps.GetUnmappedPropertyNames())
{
expression.ForMember(property, opt => opt.Ignore());
}
return expression;
}
}
最後に、Application Start Handler の下の Global.asax クラスで
AutoMapperConfigurator.Configure();
参照
パッケージマネージャーコンソールからダウンロードできます
