We have a system that does all kinds of complex and simple select queries.
We did some simple testing and got these results:
Query 3.9 seconds :
var result = (from temp in context.model
where temp.ID == 1302
select temp).First();
Start Transaction time: 17:54:58.7073806
End Transaction time: 17:55:02.6246046
Query 3.7 seconds :
Model modelResult = context.Model.Find(1302);
Start Transaction time: 17:53:51.1995194
End Transaction time: 17:53:54.8737295
I have been reading trying to figure out what the best options are. There is a lot of conversation of this topic on this site, however, I have not found exactly what I need.
I know that query choices are situational (based off the complexity of the query, etc) but in the case when we need a single entity based off a key that will not be used again (meaning, in the case of Find, caching doesn’t matter because that query is very unlikely to be called again) is it better to use direct LINQ or continue to use Find?
Is the cost of caching the results of Find, when it won’t be used, too costly? Are the results of our simple test accurate enough to assume Find will always be faster in a single entity/key situation?
I didn’t test the LINQ with turning off tracing, would this be a better approach than the two examples given?
The two are not exactly the same.
Findwill check to see if the entity has already been loaded in the context. If it has, it will just return it without performing a query. In this scenario, it will likely be far more efficient.However, if the entity is not in the context, it performs a query more like
SingleOrDefaultrather than first, which will require pulling the top two results back from the server. While there is no overhead on constructing the query, the query itself will potentially be (very slightly) slower due to that, and the results will differ, as you’ll receive errors if there is more than a single match.For more details and information, including the generated queries, see this Slauma’s answer here.