Dapper handling returned empty result set

dapper datareader

Question

We are using Dapper to map our sql data and so far it has worked very well. I have a case though where we are doing something similar to:

someObject = con.Query<T>("GetInfoSproc", p, commandType: CommandType.StoredProcedure).Single();

This works great as long as the stored procedure I'm calling returns data. There are times where the stored procedure might not return a result and return an error in a out parameter. This seems to cause a problem in Dapper because dapper throws the error:

"When using the multi-mapping APIs ensure you set the splitOn param if you have keys other than Id"

Is there a way to write the query so it can properly handle the case when an empty result is returned or is this a limitation of Dapper?

Popular Answer

SingleOrDefault() is your friend here

Try this:

someObject = con.Query<T>("GetInfoSproc", p, commandType: CommandType.StoredProcedure).SingleOrDefault();
if (someObject != null)
{
  // operate on your results here
}
return someObject;

also you'll need to make sure T is Nullable




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why