The System exception is one of the most common ones that developers run into while working with ADO.NET and databases like Oracle or SQL Server.InvalidCastException. This typically occurs when the code attempts to directly convert a NULL value from a database field to a primitive type like int or decimal.
A database null in ADO.NET is represented by the DBNull instead of the C# null keyword.object of value. Your program dies because DBNull.Value cannot be cast straight to an integer. In this post, we'll examine how to organise your data access code using a secure Try-Catch architecture and build a reliable pattern to manage these nulls by defaulting them to 0.
Background
Imagine you are fetching commission rates from an Oracle database. Your table, UTILITIES_COMPANIES_COMM_RATES, has columns for CLIENTID and COMMISSIONRATE. If a specific record has no client assigned (a NULL value), the following code will fail:
To prevent this, we must verify the data before conversion.
Step-by-Step Implementation
1. Handling DBNull with the Ternary Operator
The simplest way to fix this is to use the ternary operator (? :) to check for DBNull.Value. If the value is null, we assign a default (like 0); otherwise, we perform the conversion.
2. Implementing a Robust Repository Method
When writing for a production environment, it is best practice to wrap your database logic in a using statement (to handle connection closing) and a try-catch block (to handle errors).
Here is the full implementation for a GetAllCommissionRates method:
Creating a Cleaner Solution: Extension Methods
If you have a large project with many tables, checking for DBNull.Value in every line makes the code hard to read. We can solve this by creating a Generic Extension Method.
The Utility Class
Clean Usage
Now, your mapping code becomes much shorter and cleaner:
Summary
The Problem:
Convert.ToInt32fails when it receivesDBNull.Value.The Fix: Use
reader["column"] == DBNull.Valueto check for nulls before casting.Best Practice: Always use
usingblocks forOracleConnectionto prevent memory leaks and connection pool exhaustion.Pro Tip: Use extension methods to keep your repository code clean and maintainable.
Handling database nulls is a fundamental part of building stable .NET applications. By following the patterns above, you can ensure your application handles missing data gracefully without crashing.


0 comments:
Post a Comment