user3429672
user3429672

Reputation: 237

Entity Framework - slow when using a simple query

I have a simple class in entity framework as follows:

public class Merchandising
{
    public int Id { get; set; }

    public int Index { get; set; }    

    public int CategoryId { get; set; }

    public int? CardId { get; set; }  
}

In the database this has approximately 1000 rows, and a direct query takes less than a second, but when I execute this statement, it takes up to 55 seconds to run - which I find very bizarre. Can anyone throw any light on this?

var mm = a.Merchandisings.ToList();    
var m = mm.Where(f => f.CategoryId == catId).ToList();

catId is an integer value, and mm takes a fraction of a second to execute. There are approximately 1000 rows returned by mm, and 40 rows returned by m. M takes around 55 seconds to execute.

I am assuming that although the CategoryId and CardId both link to other classes (and are big data objects), data isn't loaded because there is no lazy loading.

I really can't understand why it is taking so long for m to execute, and I guess this is to do with some lack of knowledge with equity framework. Can anyone assist?

Upvotes: 1

Views: 145

Answers (1)

ocuenca
ocuenca

Reputation: 39326

The problem is when you call the ToList method in your first line you will bring all the elements to memory, so try filtering first to avoid load unnecessary elements that don't meet the condition, and after that call the ToList method:

var m =  a.Merchandisings.Where(f => f.CategoryId == catId).ToList();

Upvotes: 5

Related Questions