SingleOrDefault()

Posts   
 
    
tzarger
User
Posts: 87
Joined: 14-Jun-2007
# Posted on: 02-May-2008 06:15:10   

Hello,

Just curious if the extension method will eventually return null for example if the entity is not found when using SingleOrDefault() ... A niceness of LingToSql is that you can use that and simply check for null back in the middle tier, now not only would I have to do that, but in my logic layer, I would need an additional try/catch around the call if I did not want to rely on the middle teir to catch the exception...

Just curious as to if they are not implemented due to not being done yet, or will never be implemented?

Thanks Frans!

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39614
Joined: 17-Aug-2003
# Posted on: 02-May-2008 09:54:16   

tzarger wrote:

Hello, Just curious if the extension method will eventually return null for example if the entity is not found when using SingleOrDefault() ... A niceness of LingToSql is that you can use that and simply check for null back in the middle tier, now not only would I have to do that, but in my logic layer, I would need an additional try/catch around the call if I did not want to rely on the middle teir to catch the exception...

Just curious as to if they are not implemented due to not being done yet, or will never be implemented?

Thanks Frans!

SingleOrDefault is in our framework equal to Single, so if there are 0 rows, an exception is raised. All the 'Default' methods are not implemented and are equal to their non-default counterparts. The reason is that you can have SingleOrDefault ending up inside the query where it's not possible to test if there's a value or not. This would mean that if there are no rows, the 'default' has to be obeyed and an empty object has to be created. But inside a query, this isn't possible (as it's inside the db).

Single is a dumb method btw. It forces the anti-pattern 'use exceptions for control flow' upon you. It's up to the caller to check whether the returned value is indeed there or not. If you want to be sure there is just 1 value, use a count query and compare the value with 1.

So I'd use 'First' instead of Single.

Frans Bouma | Lead developer LLBLGen Pro