10

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?

John Ten Cate
  • 475
  • 5
  • 16
  • 1
    I've opened an issue on google code on this for further discussion: http://code.google.com/p/dapper-dot-net/issues/detail?id=57 – TodK Aug 01 '11 at 18:03
  • For those who may come across this question, I found [this answer](http://stackoverflow.com/questions/11720611/how-to-return-null-from-a-dapper-query-rather-than-defaultt) helpful. – Dan Hogan Mar 03 '15 at 23:06

1 Answers1

6

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

Brett Veenstra
  • 47,674
  • 18
  • 70
  • 86
  • If there is the possiblity that your SPROC may return a list of , then SingleOrDefault will throw an exception. In that case best to use FirstOrDefault. See the Dapper docs: http://dapper-tutorial.net/querysingleordefault – maurocam Jan 15 '18 at 16:04