Search code examples
c#asp.net-mvcasp.net-mvc-viewmodel

Bad performance ASP.NET MVC ViewModel


I need advice about my application.

First of all, I have two models which represent two tables (there are not the real tables)

CUSTOMERS (135K rows | 40 columns)

+-------------+--------+------------+
| CUSTOMER_ID |  NAME  | FIRST_NAME |
+-------------+--------+------------+
|        1234 | DUPONT | JEAN       |
+-------------+--------+------------+

ORDERS

+-------------+----------+-------+
| CUSTOMER_ID | ORDER_ID | TYPE  |
+-------------+----------+-------+
|        1234 |     5678 | MEET  |
|        1234 |     9105 | CANDY |
|        2568 |     7523 | CANDY |
+-------------+----------+-------+

I want to get a customer with his list of orders.

So I created a Viewmodel :

public class ViewModel
{
    public string CustomerID { get; set; }
    public string Name  { get; set; }
    public string FirstName { get; set; }
    public List<OrdersViewModel> Orders { get; set; }

    public ViewModel(){Orders = new List<OrdersViewModel>(); 
}

And now the query :

var query = from c in northwind.CUSTOMERS
            select new ViewModel()
                       {
                           CustomerID = c.CustomerID,
                           Name = c.Name,
                           FirstName = c.FirstName
                       };
var CustomersModels = query.ToList();
var queryOrders = from c in northwind.CUSTOMERS
                  join o in northwind.ORDERS
                  on c.CustomerID  equals o.CustomerID 
                  select new OrdersViewModel()
                             { 
                                 CustomerID = d.CustomerID,
                                 OrderId= d.OrderId,
                                 Type= d.Type
                             };
var modelsOrders = queryOrders .ToList();

foreach (ViewModel item in modelsOrders )
{
    var listModels = modelsOrders .Where(e => e.PMRQTOTM ==  item.PMRQTOTM).ToList();
    item.Orders = listModels;
}

Is there a better way to realise this?

I get the CustomerModel in less than 30 seconds but for the order it takes several minutes...


Solution

  • If Customer and Order has a relationship, you can use Include in first query.

    Even then you should not query 135K all at once. Instead, you want to use Skip and Take based on Page Size and Page Index.