Recently, in the applications I developed, I checked the number of rows affected by inserting, updating, deleting the database and logging the error if the number is unexpected. For example, if you simply insert, update, or delete one row, if any number of rows other than one is returned from the call to ExecuteNonQuery (), I will read the error and log it. In addition, I understand that when I print this, I donβt even try to cancel the transaction if this happens, which is not the best practice and should definitely be considered. Anyway, here is the code to illustrate what I mean:
I will have a data layer function that calls a db call:
public static int DLInsert(Person person) { Database db = DatabaseFactory.CreateDatabase("dbConnString"); using (DbCommand dbCommand = db.GetStoredProcCommand("dbo.Insert_Person")) { db.AddInParameter(dbCommand, "@FirstName", DbType.Byte, person.FirstName); db.AddInParameter(dbCommand, "@LastName", DbType.String, person.LastName); db.AddInParameter(dbCommand, "@Address", DbType.Boolean, person.Address); return db.ExecuteNonQuery(dbCommand); } }
Then the business layer calls the data layer function:
public static bool BLInsert(Person person) { if (DLInsert(campusRating) != 1) { // log exception return false; } return true; }
And in the code behind or in the view (I do both web forms and mvc projects):
if (BLInsert(person)) { // carry on as normal with whatever other code after successful insert } else { // throw an exception that directs the user to one of my custom error pages }
The more I use this type of code, the more I feel like it's overkill. Especially in the encoding / representation. Is there a legitimate reason to think that simply inserting, updating, or deleting won't actually change the correct number of rows in the database? Is it more plausible to just worry about catching the actual SqlException and then handling it instead of doing a monotonous check for the rows affected each time?
Thanks. I hope you all can help me.
UPDATE
Thanks to everyone for taking the time to respond. I still have not 100% decided which setting I will use in the future, but here's what I removed from all your answers.
- Trust the database and .Net libraries to process the request and do your work as they are created.
- Use transactions in my stored procedures to roll back the request for any errors, and potentially use
raiseerror to throw these exceptions back into the .Net code as a SqlException that could handle these errors with try / catch. This approach will replace the problem return code verification.
Will there be a problem with the second number of the marker that I am missing?