Skip to main content

Posts

Showing posts from May, 2015

Using LINQ to Entity efficiently with First/FirstOrDefault/Last/LastOrDefault/Single/SingleOrDefault

We generally use these extension methods First/FirstOrDefault/Last/LastOrDefault/Single/SingleOrDefault with predicates like ctx=> ctx.Model.FirstOrDefault(item => item.Id == 1 ) Or ctx=> ctx.Model.Where(item => item.Id == 1 ).FirstOrDefault() What is the problem with these? FirstOrDefault or similar methods immediately loads all data at once. So, let's say we have fifty columns on table then all those columns data would be retrieved from DB and saved into memory. This link gives a fair idea of different function behavior.  https://msdn.microsoft.com/en-us/library/bb882641.aspx .  So, even if we require only one value from selected field it retrieves all values. What is the solution? The solution is pretty simple. Whenever we need selected items better to do projection before calling FirstOrDefault or similar methods. Ex: Selecting single item ctx.Model.Where(itm => itm.Id == 1) .Select(itm => itm.Name).FirstOrDefault()