FirstOrDefault

Posts   
 
    
Jez
User
Posts: 198
Joined: 01-May-2006
# Posted on: 24-Mar-2008 12:39:36   

Hi Frans

If I run this query:


var query = from c in meta.Customer
        where c.CustomerId == "CustomerThatDoesNotExist"
        select c;

Console.WriteLine(query.FirstOrDefault() == null);

Then an "ArgumentOutOfRange" exception is thrown because the query returns no results (which is the same behaviour as calling First()).

With Linq to SQL I can use FirstOrDefault to return null if the query yields no results...is there any reason why this isn't supported?

Thanks

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39612
Joined: 17-Aug-2003
# Posted on: 24-Mar-2008 14:46:02   

the 'Default' is misleading.

var q= from c in metaData.Customer.Where(c=>c.Country=="UK").FirstOrDefault() join o in metaData.Order on ....

what to do there? Result in 'null' ? What if I have a nested scalar... what to do there?

So 'OrDefault' variants work the same as First etc. (described in the doc).

Now back to your query. It shouldn't throw up in an exception. I'll check it out.

(edit). Ok this is a bug in LLBLGenProProviderBase.TResult IQueryProvider.Execute<TResult>(LinqExpression expression)

it always assumes there's a value. It should check if there's a value. Will fix it.

Frans Bouma | Lead developer LLBLGen Pro
Jez
User
Posts: 198
Joined: 01-May-2006
# Posted on: 24-Mar-2008 14:56:48   

Ah right, I assumed that First was supposed to throw an exception (as Linq2Sql throws too) while FirstOrDefault should returns null.

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39612
Joined: 17-Aug-2003
# Posted on: 24-Mar-2008 14:59:12   

Jez wrote:

Ah right, I assumed that First was supposed to throw an exception (as Linq2Sql throws too) while FirstOrDefault should returns null.

That's in theory a great idea, but in practise it doesn't work simple_smile => If the 'First' is a nested query, you can't throw an exception. It's the same as with 'Single'. Single can't determine if the set is exactly 1 element if the Single query becomes a nested query.

First / FirstOrDefault now both return null in the query you showed. I can't find a requirement in the First() documentation that it should throw an exception if there aren't any values.

Frans Bouma | Lead developer LLBLGen Pro