プロジェクトで Asp.Net MVC、C#、EF 6 CodeFirst を使用しています。一部のビューでは、ViewModel を作成したため、複数のエンティティからプロパティを表示する必要があります。AutoMapper (オブジェクト マッパー) を使用する代わりに、ViewModel を Model (データベース オブジェクト) にマップするために、独自の方法を実装しようとしています。ViewModel クラスでは、GetViewModel() という名前の静的メソッドと、モデルからビュー モデルへのマッピング オブジェクトを作成しました。そのまま使えるかな。パフォーマンスに適していますか、それとも問題を引き起こしますか。Webアプリだから?
public class CustomerViewModel
{
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public string Locations{ get; set; }
public static CustomerViewModel GetCustomerWithFullAddress(Customer customer)
{
try
{
CustomerViewModel viewModel = new CustomerViewModel();
viewModel.CustomerId = customer.CustomerId;
viewModel.CustomerName = customer.CustomerName;
foreach(Address address in customer.Addresses){
viewModel.Locations = viewModel.Locations +"," + address.Country;
}
return viewModel;
}
catch (Exception ex)
{
throw ex;
}
}
}
次に、コントローラーでこのようにアクセスできます。
Customer customer= db.Customer.Where(x => x.CustomerId == 1).FirstOrDefault();
CustomerViewModel response = CustomerViewModel.GetViewModel(customer);