Reputation: 74008
I use asp.net 4 c# and EF 4.
I'm profiling my application. I have this code which result expensive.
I woud like to know if you know a better way to write it. I need to speed it up.
string htmlhead = context.CmsOptions.SingleOrDefault(op => op.OptionId == 7).Value;
if (htmlhead != null)
uxHtmlHead.Text = htmlhead;
else
uxHtmlHead.Text = "No Html Head.";
Thanks
Useful article http://weblogs.asp.net/zeeshanhirani/archive/2010/09/20/which-one-is-faster-singleordefault-or-firstordefault.aspx
Upvotes: 2
Views: 4269
Reputation: 39898
There are some basic steps you can take when optimizing an Entity Framework query.
Here you can find a list of all the options.
The ones I would suggest in your case are:
If you are using Visual Studio Premium you could put this code in a Unit Test and then profile the unit test. After each change you can compare the reports to make sure you are improving performance.
Upvotes: 1
Reputation: 13594
Use FirstOrDefault()
... This will exit as soon as it finds a result.
On the other hand SingleOrDefault()
searches the entire collection for a single result and throws exception if it finds more than one result for the query
Upvotes: 13