Camille Rethoret
Camille Rethoret

Reputation: 75

Handling null result

I have a db request that could return null:

Pony MyPony = db.Pony.Where(p => p.PonyOwnerId == user.UserId).First();

If there is no row in my db, there is an error message.

How to accept an empty query?

Upvotes: 1

Views: 88

Answers (3)

spajce
spajce

Reputation: 7092

var MyPony = db.Pony.FirstOrDefault(p => p.PonyOwnerId != null && p.PonyOwnerId == user.UserId);

or

var MyPony = db.Pony.Where(p => p.PonyOwnerId != null && p.PonyOwnerId == user.UserId).FirstOrDefault();

or

if (db.Pony.FirstOrDefault(p => p.PonyOwnerId != null && p.PonyOwnerId == user.UserId) != null)
{
 //Do stuff
}

Upvotes: 2

devdigital
devdigital

Reputation: 34349

You can use FirstOrDefault

Pony myPony = db.Pony.Where(p => p.PonyOwnerId == user.UserId).FirstOrDefault();

if (myPony == null) 
{ 
    .. 
}

Upvotes: 2

Roberto Conte Rosito
Roberto Conte Rosito

Reputation: 2108

You can write:

Pony myPony = db.Pony.Where(p => p.PonyOwnerId == user.UserId).FirstOrDefault();
if( myPony != null ) {
    // Do something
}

Upvotes: 2

Related Questions