I have a method doing some linq operations that is taking over a minute to take 4,000 rows from SQL and place them into a list of objects. What I am trying to do can be summed down to:
- Get all rows from table
- Cast each row to a corresponding object based on the rows fields
- Return a list of that object
In other words, I have an object that corresponds to a row in my database and I want linq to return back a list of all the objects in the table those rows sit in.
What I’m doing is this:
public List<Article> GetAllArticlesFromDB()
{
using (DBEntities le = new DBEntities(this._efConnectionString))
{
IQueryable<ARTICLE> x = from row in le.ARTICLE select row;
List<Article> llr = x.Select(r => new Article
{
ArticleNumber = r.ARTICLE_NUMBER,
ArticleTitle = r.TITLE,
}).ToList();
return llr;
}
}
Trouble is, this query takes over a minute. There are only two fields, one is an int, the other a string of max length 255. A simple SQL query on it works in less than a second. But this linq query takes over a minute. Can I optimize this somehow?
Which Entity Framework Context approach are you using for your entities? The “old” entity framework approach generates context objects which are all
EntityObjectderived objects and introduce much overhead, and constructing 4000 of them might take quite long. A better approach is to use POCO objects, they are quite small and fast, but you might need to use a different generator if you are using Visual Studio 2010 and/or EF 4 (in contrast to VS 2012 and EF5 which allows generation of POCO entities out of the box).Which EF Version and which approach are you using?
Here is a nice tutorial showing how to get the new
DbContextapproach (for database first scenarios) working.