H. Rashid
H. Rashid

Reputation: 172

Mapping List<T> to a model in ASP.NET MVC5

I am trying to map my model with the view model and I guess this isn't the most efficient way. Here is the code:

List<hall> allHalls = db.halls.Take(30).ToList();
List<HallViewModel> HVMLIST = new List<HallViewModel>();

int process = 0;

foreach(var hall in allHalls)
{
    havvViewModel HVM = new havvViewModel();
    HVM.name = hall.name;
    ...

}

Is there a more efficient way to do this? Will calling havvViewModel HVM = new havvViewModel(); in a for loop create a performance issue since I'm making a new object every time? Please Advise...

Upvotes: 1

Views: 2097

Answers (2)

GHP
GHP

Reputation: 3231

As @labilbe commented, unless you are constructing thousands and thousands of objects in that loop, its going to execute instantly. My preference is to have one ViewModel per "screen" (roughly) and if I had a page that rendered a list of halls, I'd compose the ViewModel like

public class HallListing : BaseViewModel
{
     private List<hall> halls;
     public void LoadData() 
     {
          this.halls = base.db.halls.Take(30).ToList();
     }
}

abstract class BaseViewModel 
{
     protected DataContext db { get; private set; }
     public BaseViewModel() 
     {
          this.db = new DataContext();
     }
}

Upvotes: 0

Philip Pittle
Philip Pittle

Reputation: 12295

The way your code is written, there really isn't anything wrong with it from a performance standpoint. Creating a new object is a relatively inexpensive operation (assuming there isn't any work being done in the constructor) and creating 30 objects is nothing to be concerned about.

If you wanted to you could make your code linq-y. This won't really have a performance impact, but it looks cool :)

return 
    db.halls
      .Take(30)
      .Select(h => 
          new havvViewModel
          {
              Name = h.name
          });

Upvotes: 1

Related Questions