I am trying to fetch business model entities from database and then iterate them to search a string. However, in my localhost this operation takes approximately 7 to 9 seconds for 500 objects.
public List<FileFolder> SearchFolders(int id, string searchString)
{
/* Placeholder that references folders that passes search criteria */
List<FileFolder> addedFolders = new List<FileFolder>();
/* Get the folder with specified id, also include Folders
* that this folder has. No problem here works perfectly fine
* and fast */
FileFolder folder = dbSet.Include("Folders").
.Where(q => q.FileFolderID == id)
.ToList().FirstOrDefault();
/* This takes too much time as I mention, up to 9 seconds
* for 500 Folders */
foreach (FileFolder f in folder.Folders)
{
if (f.Name.Contains(searchString))
{
addedFolders.Add(f);
}
}
return addedFolders;
}
I am converting my fetched data to List so I can safely say all the data is now in memory? So foreach loop should not be making any more db calls while accessing folders. Also I have checked .Include method and it is is working fine.
What might be the cause of this slow iteration?
Thanks.
Remember, this is linq. Things don’t happen right away. It does not actually start running the query before the first iteration of the
foreach().What is really slow in this query is this
The real question is how is dbSet’s “Folders” defined. Do you have lots of FK joins built in? If so a simple request like this can pull your whole database. It all depends on what depends on “Folders”.
You can even see this in the debugger, as you step over the foreach loop you will see it “pop” back to the linq line.