22

I am using PetaPoco Micro-ORM with C# 4.0.

The code below retrieves a single row from the database:

var result = db.SingleOrDefault<TdUsers>(getUserQuery);

I would like to check whether or not the result contains any rows, and whether is null. What is the best way to do this?

Troy Alford
  • 26,660
  • 10
  • 64
  • 82
RKh
  • 13,818
  • 46
  • 152
  • 265

4 Answers4

33
if (result == null || result.Count() == 0) {
    // Checks whether the entire result is null OR
    // contains no resulting records.
}

I think the problem is not in your check for null, because linq is lazy loading. Your error is in using the expression db.SingleOrDefault<TdUsers>(getUserQuery);.

.Single<T>(expression) does not return null - it errors if the result returns no values. .SingleOrDefault<T>(expression), however, returns a null value if the expression results in no values - and therefore is best combined with an if (result == null) type check, as you're using here.

AutomatedChaos
  • 7,267
  • 2
  • 27
  • 47
Parv Sharma
  • 12,581
  • 4
  • 48
  • 80
5
var result = db.SingleOrDefault<TdUsers>(getUserQuery);

In above code SingleOrDefault will return null vale or the specified generic type(it's known on runtime).

Inorder to check whether the returned values is null or not you can simply use

if(result!=null)
{
//do your code stuff 
}
else
{
//stuff do be done in case where result==null
}
shanky
  • 376
  • 1
  • 18
4

You could do:

result.ToList() // Convert result to a list

if (result.Any()) {
   // result is not null
}
Darren
  • 68,902
  • 24
  • 138
  • 144
  • NO result==null wont be false always.. what do you think is the default value of any reference type? – Parv Sharma May 25 '12 at 11:49
  • 1
    This approach won't work in every case, because `result` could be null, at which point you will get a `NullReferenceException` thrown when `.ToList()` or `.Any()` are called. – Troy Alford Aug 08 '12 at 22:03
2
 var v = result.ToList();

now check

if (v is not null)
{

}
else if (v.Count()>0)
{


}
Romil Kumar Jain
  • 20,239
  • 9
  • 63
  • 92