-2

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);
HarisJayadev
  • 92
  • 12
  • _"Is it good for performance or will it create any issue"_ - this is opinion-based and too broad. What (performance) issues do you expect and why?What do you want answers to teach you? What have you researched for yourself? – CodeCaster Jul 01 '15 at 11:28
  • I have used automapper. Its too slow to map object. That's the reason I have tried this. But before move this to production I need to confirm the way I have implemented. – HarisJayadev Jul 01 '15 at 15:35
  • AutoMapper is not slow. You're dealing with an HTTP POST here, chances are your mapping code is the fastest code in the entire pipeline. Anyway we can't confirm this for you. You also don't move code into production directly, that's what testing/acceptance environments are for. – CodeCaster Jul 01 '15 at 16:03

2 Answers2

0

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".

JNN
  • 38
  • 2
-1

It is a perfectly good way to map your model to a view model. So go ahead and use it.

stann1
  • 576
  • 3
  • 11