views:

267

answers:

2

I'm using LINQ to SQL to call a stored procedure. This stored procedure currently returns a resultset and then has some raiserror statements being triggered after the resultset is retrieved (I'm writing tests for stored procedures, in case you're wondering why I'm doing this).

When LINQ to SQL calls the proc and it gets a resultset back, it seems to ignore all of the errors that I'm throwing because it got its resultset. Is there a way to make it always throw a SqlException when I do a raiserror from SQL?

+1  A: 

Make sure that your Severity Level is greater than 10 when you call RAISERROR as per:

http://support.microsoft.com/default.aspx/kb/321903

RAISERROR('Stored Procedure Execution Failed',15,1)
Jonathan Kehayias
yeah, my severity level is 16.
Jon Kruger
+2  A: 

Interesting; that is a problem I have seen before when using an IDataReader, which is why I now religiously consume all the tables (even if I am only expecting one) - for example, if I am only expecting one table, something like:

    while (reader.Read())
    { // read data from first table

    }
    // read to end of stream
    while (reader.NextResult()) { }

The problem is that the error goes into the TDS at the point you raise it; so if you raise it after the SELECT then in follows table in the TDS - and if the reader doesn't read to the end of the stream they might not see it.

I'll be honest - my preferred answer to this is: raise all errors before data. This might mean doing the main SELECT into a temp-table (#table) or table-variable (@table). Beyond that - if it is critical to catch this error (and if the inbuilt LINQ-to-SQL code isn't helping), then perhaps fall back to ExecuteReader and something like the above.

I suspect (but I haven't checked) that you could also use DataContext.Translate<T> to do some of the ORM heavy-lifting; for example:

// cmd is our DbCommand, and ctx is our DataContext
using(var reader = cmd.ExecuteReader()) {
   var result = ctx.Translate<MyResultType>(reader).ToList();
   while(reader.NextResult()) {}
   return result;
}
Marc Gravell