Will this SingleOrDefault () optimization be worthwhile or will it be excessive / harmful?

I messed around with LinqToSQL and LINQPad, and I noticed that SingleOrDefault () does not do any filtering or limitation in the generated SQL (I almost expected the Take (1) equivalent).

So, assuming that you want to protect yourself from large numbers accidentally returned, will the following snippet be useful or is this 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;
}

Unlike the usual way, I would do it (pay attention to .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 realized with Take (2), I still get the functionality of SingleOrDefault () with the added benefit of never worrying about returning {n} rows by accident, but I'm not sure if it's even worth it if I constantly expect a random return {n} lines with my request.

, ? ? - pro/con, ?

Edit:

SQL, Take (2)


SELECT [t0].[blah], (...) 
FROM [dbo].[Single] AS [t0]
WHERE [t0].[ID] = @p0

SQL, Take (2)


SELECT TOP 2 [t0].[blah], (...) 
FROM [dbo].[Single] AS [t0]
WHERE [t0].[ID] = @p0

, SingleOrDefault, , , 2 , "Take (2)". , .Take(2) {n} , 2 (, ).

+3
4

Single - , . Single, , , : " , , ", someArray[0], , . SingleOrDefault null , 0. Single SingleOrDefault , : a InvalidOperationException .

ID UNIQUE, , 1 TOP.

, non-unique/non-key ( , , OrderBy), First Last ( OrDefault ), SQL, :

var query = from s in context.Singles 
            where s.Id == id
            orderby s.someOtherColumn
            select s;

var item = query.FirstOrDefault();

, :

var query = from s in context.Singles where s.Id == id select s;
var item = query.SingleOrDefault();

:

var item = context.Singles.SingleOrDefault(s => s.Id == id);
+3

SingleOrDefault ( IEnumerable <T> .SingleOrDefault( )) InvalidOperationException, .

- .


Edit:

. , , , .Take(2). , .

SingleOrDefault() , > 1 . , . , , , > 2 .Take(2), , . . .

+2

. , , . - SingleOrDefault() , . , , .

UPDATE

, . , , . Single(), First(), Take(1) - . - Single(), , . , , - , - . , .

+2

Allen, ID - primary key for Singles table? If this I do not quite understand your problem, since your second request will return a single record or null. And SQL will be where ID = ### ... Using Take (2) .SingleOrDefault () defeats the target of SingleOrDefault.

0
source

Source: https://habr.com/ru/post/1707785/


All Articles