Skip to content

QueryFirst<> Ignores SQL Error #1834

Open

Description

@a-teece

We had a bug in a stored proc that left a transaction open. Completely understand this is a bug in non-Dapper code however I feel Dappers handling of SQL Errors is flawed, inconsistent with other Dapper methods and dangerous.

Take a simple SP that replicates our problem:
BEGIN TRANSACTION
INSERT INTO....
SELECT .....

When you call this SP from Management Studio you get the error: "Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 0, current count = 1."

When you call this SP using .net native SqlCommand you get an SqlException with the same error.
When you call this SP using .net native SqlCommand ExecuteReader() you don't get this exception unless you iterate all the results with NextResult() at which point you get an SqlException with the same error.
When you call this SP using Dapper .Execute you get a SqlException with the same error.
When you call this SP using Dapper .QueryFirst you get a result, no exception.

Regardless of the scenario it feels wrong to me that QueryFirst would ignore an error returned from SQL server just because there is a successful result included as well. This is any error not just my transaction example. Any business logic using RAISERROR/query mistake goes un-noticed and could be within a .net TransactionScope which now gets committed.

This does appear standard behaviour in .net for ExecuteReader(), but can be solved by always calling NextResult() until there are no more results. This would feel much safer to me; i'd rather always know if there is a bug rather wait for some obscure symptom.

Activity

  1. mgravell commented on Oct 4, 2022

    @mgravell
    Member

    This is intriguing. I'm very aware of the need to iterate a result to conclusion, and that should be something Dapper is doing internally already. If it isn't somehow, that's an oversight. I need to have a look at this!

    (Dapper has always taken the view that you shouldn't need to know all these nuances and edge cases: that's the tool's job to get right; so: I absolutely agree with you here)

  2. a-teece commented on Oct 4, 2022

    @a-teece
    Author

    @mgravell Found this article talking about the .net "base" logic on this which highlights the same: https://taeguk.co.uk/blog/sqldatareader-gotcha/

  3. mgravell commented on Oct 11, 2022

    @mgravell
    Member
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions