Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper handling returned empty result set

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?

like image 204
John Ten Cate Avatar asked Jul 29 '11 18:07

John Ten Cate


People also ask

Does dapper return null?

In this method, the query has the option to return nothing without risking a thrown exception in Dapper. This method API returns exactly one object or the default value which is typically null.

What is QueryAsync in Dapper?

The provider is just an abstraction on creating a database connection (SqlConnection) and returns an IDbConnection. We use that connection to call the QueryAsync method. QueryAsync is exactly what it sounds like, it asynchronously queries your database and maps it back to an object (in this case a Car object).

Is Dapper case sensitive?

Dapper's(SqlMapper) Query method over the Connection factory runs the SQL query, then maps the database result to Employee class and returns as a list of employees. Note : Only matching class and table properties are mapped to list of employee, they are case sensitive.


1 Answers

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

like image 167
Brett Veenstra Avatar answered Sep 22 '22 20:09

Brett Veenstra