简体   繁体   中英

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

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
          });

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();
     }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM