Why does Dapper's .Execute(...) return an int?

24,937

Solution 1

The integer represents the number of rows that were affected by your query.

It returns an integer so you know if your query has worked. If zero is returned and you expected something to have changed then you know there is a problem.

Solution 2

Because DbCommand.ExecuteNonQuery (which Dapper uses internally, no doubt) returns an int for the number of rows affected. Why? Because it's more or less free, and is about the only thing that you can reasonably return for a generic INSERT or UPDATE.

Share:
24,937
Drew R
Author by

Drew R

Updated on October 31, 2020

Comments

  • Drew R
    Drew R over 3 years

    Anyone know why Dapper returns an int from .Execute(...) ?

    I can't find this documented anywhere.

  • Drew R
    Drew R over 8 years
    Thanks! @RahulTripathi this answers both for me :)
  • Drew R
    Drew R over 8 years
    This should have given it away!
  • JustLooking
    JustLooking over 4 years
    But 0 may be OK. For example, let's say you are updating a record, but before you execute, it's deleted out from under you (and let's say that's OK). I'd like a little more details about this return code. Will it return 0 for when the record isn't there (like my example) and if there was some type of failure (which I would probably want to act on in a different way)? Or is failure always going to result in an exception?
  • CathalMF
    CathalMF over 4 years
    @JustLooking A record not existing isn't a failure. So you will just get a zero response.
  • JustLooking
    JustLooking over 4 years
    @CathalMF -- I agree. Maybe I wasn't clear, my bad. What I'm saying is that I think the record not found should return 0. But are there instances outside of record not found that will also return 0? For example, some type of failure. Or instead, will all failures be an exception. Thus, it returns 0 for not found, 1 (or more) for actual records affected, exception for failure.
  • JustLooking
    JustLooking over 4 years
    Or someone at least point me to good dapper documentation. Take a look at microsoft. As an example, I'm looking at DataAdapter Update documentation. It says it returns an Int32 (rows updated) and then it lists the exceptions it throws. Perfect! Where's the Dapper equivalent?
  • CathalMF
    CathalMF over 4 years
    Yes actual failures will result in an exception. Dapper is open source. Look at the code on GitHub to see what it does.