简体   繁体   English

映射表 <T> 到ASP.NET MVC5中的模型

[英]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(); 将调用havvViewModel HVM = new havvViewModel(); in a for loop create a performance issue since I'm making a new object every time? 在for循环中会产生性能问题,因为每次都在创建一个新对象? 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. 创建一个新对象是一个相对便宜的操作(假设构造函数中没有做任何工作),创建30个对象无关紧要。

If you wanted to you could make your code linq-y. 如果您愿意,可以将代码设为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. 正如@labilbe所评论的那样,除非您在该循环中构造成千上万的对象,否则它将立即执行。 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 我的偏好是每个“屏幕”(大约)有一个ViewModel,如果我有一个呈现大厅列表的页面,我会像这样组成ViewModel

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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