【发布时间】:2015-09-18 08:21:10
【问题描述】:
我在我的项目中使用 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);
【问题讨论】:
-
“它对性能有好处还是会产生任何问题” - 这是基于意见的,过于宽泛。您期望什么(性能)问题以及为什么?您希望答案教给您什么?你为自己研究了什么?
-
我用过自动映射器。映射对象太慢了。这就是我尝试这个的原因。但在将其投入生产之前,我需要确认我实施的方式。
-
AutoMapper 并不慢。您在这里处理的是 HTTP POST,您的映射代码很可能是整个管道中最快的代码。无论如何,我们无法为您确认这一点。您也不会将代码直接移入生产环境,这就是测试/验收环境的用途。
标签: c# asp.net-mvc entity-framework object-object-mapping