How to optimize this code?

4

Is there a faster (performative) way of comparing the current value with the previous value (of the bank) with Entity Framework ? Instead of selecting Id by Id (as Discount property of the code below), check the array integer, or something of the type?

With the code below, I check the last price of the value and calculate the discount, however, it is done Id by Id .

ha.AddRange(
    array.Select(
        x => new ProductHistory {
            ProductId = x.Id
                , Price = x.Price
                , LastUpdate = DateTime.Now.Date
                , Discount = x.Price / (
                    (Convert.ToDecimal(db.ProductHistory.Where((ProductHistory p) => x.Id == p.ProductId)
                        .OrderByDescending(o => o.LastUpdate)
                        .Select(y => y.Price)
                        .FirstOrDefault()) == 0) ? x.Price :
                    (Convert.ToDecimal(db.ProductHistory.Where((ProductHistory p) => x.Id == p.ProductId)
                        .OrderByDescending(o => o.Id)
                        .Select(y => y.Price)
                        .FirstOrDefault()))) * 100 - 100
        }
    )
);
    
asked by anonymous 18.11.2015 / 20:08

1 answer

6

What you're doing is lousy in performance. My suggestion is:

// Selecione todos os Products envolvidos no que você quer.
// Adiante ProductHistory. Include() usa INNER JOIN.
var allProducts = db.Products
                    .Include(p => p.ProductHistory)
                    .Where(...).ToList();

// Aqui uso apenas operações em memória. 
// O jeito que você estava fazendo abria vários SQL em sequência, 
// o que não vale a pena pra operação que você está fazendo.
foreach (var element in array)
{
    var product = allProducts.FirstOrDefault(p => p.Id == element.ProductId);
    var lastUpdateHistory = product.ProductHistory.OrderBy(ph => ph.LastUpdate).FirstOrDefault();
    var lastId = product.ProductHistory.OrderByDescending(ph => ph.Id).FirstOrDefault();
    element.Discount = lastUpdateHistory.Price > 0 ? array.Price : lastId.Price * 100 - 100;
}
    
18.11.2015 / 20:49