我在我的项目中使用 Asp.Net MVC、C#、EF 6 CodeFirst。在某些视图中,我需要来自多个实体的显示属性,为此我创建了 ViewModel。现在要将 ViewModel 映射到模型(数据库对象)而不是使用 AutoMapper(对象映射器),我正在尝试实现自己的方式。在 ViewModel 类中,我创建了名为 GetViewModel() 的静态方法并将对象从模型映射到视图模型。我可以这样用吗。它对性能有好处还是会产生任何问题。因为它是网络应用程序。?
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);