I was messing around with LinqToSQL and LINQPad and I noticed that SingleOrDefault() doesn't do any filtering or limiting in the generated SQL (I had almost expected the equivalent of Take(1)).
So Assuming you wanted to protect yourself from large quantities accidentally being returned, would the following snippet be useful or is it a bad idea?
// SingleType is my LinqToSQL generated type
// Singles is the table that contains many SingleType's
// context is my datacontext
public SingleType getSingle(int id)
{
var query = from s in context.Singles where s.ID == id select s;
var result = query.Take(2).SingleOrDefault();
return result;
}
As opposed to the normal way I would have done it (notice no .Take(2) )
public SingleType getSingle(int id)
{
var query = from s in Singles where s.ID == id select s;
var result = query.SingleOrDefault();
return result;
}
I figured with the Take(2), I would still get the functionality of SingleOrDefault() with the added benefit of never having to worry about returning {n} rows accidentally, but I'm not sure if its even worth it unless i'm constantly expecting to accidentally return {n} rows with my query.
So, is this worthwhile? Is it harmful? Are there any pro's / con's that I'm not seeing?
Edit:
SQL Generated without the Take(2)
SELECT [t0].[blah], (...)
FROM [dbo].[Single] AS [t0]
WHERE [t0].[ID] = @p0
SQL Generated with the Take(2)
SELECT TOP 2 [t0].[blah], (...)
FROM [dbo].[Single] AS [t0]
WHERE [t0].[ID] = @p0
Also, when I speak of SingleOrDefault's functionality, I specifically desire to have it throw an exception if 2 or more are returned, which is why i'm doing a "Take(2)". The difference being, without the .Take(2), it will return {n} rows from the database, when it really only needs to return 2 (just enough to make it throw).