I'm using Asp.Net MVC,C#,EF 6 CodeFirst in my project. In some Views I need display properties from more than one entity, for that i have created ViewModel. Now to map ViewModel to Model(Database object) instead of using AutoMapper (Object Mapper's), I'm trying to implement my own way. In ViewModel class I have created static method named GetViewModel() and mapping objects from Model to view model. Can i use like that. Is it good for performance or will it create any issue. Since it is web application.?
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;
}
}
}
Then in controller I can access like this .
Customer customer= db.Customer.Where(x => x.CustomerId == 1).FirstOrDefault();
CustomerViewModel response = CustomerViewModel.GetViewModel(customer);
AutoMapper is not slow, assuming that the definition of the mappings is in the constructor, which happens once in a call to a class when it is being initialized. You can try adding a stopwatch that logs the time to trace, to really determine if it is "too slow".
It is a perfectly good way to map your model to a view model. So go ahead and use it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.