NetEvolve.Extensions.Data is a powerful .NET library that provides essential extension methods for working with data access components from the System.Data namespace. The library is designed to simplify data handling operations, reduce boilerplate code, and improve developer productivity when working with databases in .NET applications.
This package contains multiple extensions for native .NET components, especially for the System.Data namespace. The main goal is to provide a set of time-saving methods that simplify development in the context of data handling, with a focus on:
- Null-safe data retrieval from database readers and records
- Type-safe generic methods for accessing field values
- Async/await support for modern asynchronous programming patterns
- Column existence checking to avoid runtime exceptions
- Default value handling for nullable database fields
- HasColumn() - Check if a column exists in the data reader before accessing it
- Prevents
IndexOutOfRangeExceptionwhen working with dynamic queries
- GetNullable*() methods for all primitive types (Boolean, Byte, Char, DateTime, Decimal, Double, Float, Guid, Int16, Int32, Int64, String)
- Safe retrieval of nullable values with configurable default values
- Support for both column index and column name access
- GetFieldValue<T>() by column name (generic type-safe access)
- GetFieldValueAsync<T>() for asynchronous operations
- GetFieldValueOrDefault<T>() with fallback values for null columns
- GetFieldValueOrDefaultAsync<T>() for async operations with defaults
dotnet add package NetEvolve.Extensions.Data<PackageReferenceInclude="NetEvolve.Extensions.Data"Version="1.0.0" />- .NET Standard 2.0 (compatible with .NET Framework 4.6.1+, .NET Core 2.0+, .NET 5+)
- Multi-target support: .NET 8, .NET 9
All extension methods are available in the NetEvolve.Extensions.Data namespace.
usingNetEvolve.Extensions.Data;usingvarcommand=connection.CreateCommand();command.CommandText="SELECT Id, Name, Email FROM Users";usingvarreader=command.ExecuteReader();while(reader.Read()){// Safe column checking before accessif(reader.HasColumn("Email")){varemail=reader.GetString("Email");}// Avoid runtime exceptions for optional columnsvarphoneExists=reader.HasColumn("Phone");// Returns false if column doesn't exist}usingvarcommand=connection.CreateCommand();command.CommandText="SELECT Id, Name, Age, IsActive, Salary, CreatedDate FROM Users";usingvarreader=command.ExecuteReader();while(reader.Read()){varid=reader.GetInt32("Id");// Regular access for non-null columnsvarname=reader.GetString("Name");// Null-safe access with default valuesvarage=reader.GetNullableInt32("Age");// Returns null if DBNullvarageWithDefault=reader.GetNullableInt32("Age",0);// Returns 0 if DBNullvarisActive=reader.GetNullableBoolean("IsActive",false);// Returns false if DBNullvarsalary=reader.GetNullableDecimal("Salary");// Returns null if DBNullvarcreatedDate=reader.GetNullableDateTime("CreatedDate");// Returns null if DBNull// Using column index instead of namevaremailByIndex=reader.GetNullableString(3,"no-email@example.com");}// Nullable primitive types with default valuesvarnullableBool=record.GetNullableBoolean("IsActive",false);varnullableByte=record.GetNullableByte("StatusCode",0);varnullableChar=record.GetNullableChar("Grade",'N');varnullableDateTime=record.GetNullableDateTime("LastLogin",DateTime.Now);varnullableDecimal=record.GetNullableDecimal("Price",0.0m);varnullableDouble=record.GetNullableDouble("Rating",0.0);varnullableFloat=record.GetNullableFloat("Score",0.0f);varnullableGuid=record.GetNullableGuid("UniqueId",Guid.Empty);varnullableInt16=record.GetNullableInt16("SmallNumber",0);varnullableInt32=record.GetNullableInt32("Count",0);varnullableInt64=record.GetNullableInt64("BigNumber",0L);varnullableString=record.GetNullableString("Description","N/A");varnullableValue=record.GetNullableValue("CustomColumn");usingvarcommand=connection.CreateCommand();command.CommandText="SELECT Id, Name, CreatedDate, IsActive FROM Users";usingvarreader=command.ExecuteReader();while(reader.Read()){// Generic type-safe access by column namevarid=reader.GetFieldValue<int>("Id");varname=reader.GetFieldValue<string>("Name");varcreatedDate=reader.GetFieldValue<DateTime>("CreatedDate");varisActive=reader.GetFieldValue<bool>("IsActive");// With default values for nullable columnsvaremail=reader.GetFieldValueOrDefault<string>("Email","no-email@example.com");varlastLogin=reader.GetFieldValueOrDefault<DateTime?>("LastLogin");// Using column ordinalvaridByOrdinal=reader.GetFieldValueOrDefault<int>(0,-1);}usingvarcommand=connection.CreateCommand();command.CommandText="SELECT Id, Name, Data FROM LargeTable";usingvarreader=awaitcommand.ExecuteReaderAsync();while(awaitreader.ReadAsync()){// Async field value retrievalvarid=awaitreader.GetFieldValueAsync<int>("Id");varname=awaitreader.GetFieldValueAsync<string>("Name");// Async with default valuesvardata=awaitreader.GetFieldValueOrDefaultAsync<byte[]>("Data",Array.Empty<byte>());// With cancellation tokenusingvarcts=newCancellationTokenSource(TimeSpan.FromSeconds(30));varlargeField=awaitreader.GetFieldValueOrDefaultAsync<string>("LargeTextField","",cts.Token);}publicclassUserService{privatereadonlyIDbConnection_connection;publicUserService(IDbConnectionconnection){_connection=connection;}publicasyncTask<IEnumerable<User>>GetUsersAsync(CancellationTokencancellationToken=default){varusers=newList<User>();usingvarcommand=_connection.CreateCommand();command.CommandText=""" SELECT Id, FirstName, LastName, Email, Phone, IsActive, CreatedDate, LastLoginDate, ProfileImageData FROM Users WHERE IsDeleted = 0 """;usingvarreader=awaitcommand.ExecuteReaderAsync(cancellationToken);while(awaitreader.ReadAsync(cancellationToken)){varuser=newUser{Id=reader.GetFieldValue<int>("Id"),FirstName=reader.GetFieldValue<string>("FirstName"),LastName=reader.GetFieldValueOrDefault<string>("LastName",""),Email=reader.GetNullableString("Email"),Phone=reader.GetNullableString("Phone","N/A"),IsActive=reader.GetNullableBoolean("IsActive",true),CreatedDate=reader.GetFieldValue<DateTime>("CreatedDate"),LastLoginDate=reader.GetNullableDateTime("LastLoginDate"),ProfileImage=awaitreader.GetFieldValueOrDefaultAsync<byte[]>("ProfileImageData",Array.Empty<byte>(),cancellationToken)};users.Add(user);}returnusers;}}publicclassUser{publicintId{get;set;}publicstringFirstName{get;set;}=string.Empty;publicstringLastName{get;set;}=string.Empty;publicstring?Email{get;set;}publicstring?Phone{get;set;}publicboolIsActive{get;set;}publicDateTimeCreatedDate{get;set;}publicDateTime?LastLoginDate{get;set;}publicbyte[]?ProfileImage{get;set;}}| Method | Description |
|---|---|
HasColumn(string name) | Determines whether the data reader contains a column with the specified name |
| Method | Description |
|---|---|
GetNullableBoolean(int i, bool? defaultValue = null) | Retrieves a nullable Boolean from column index |
GetNullableBoolean(string name, bool? defaultValue = null) | Retrieves a nullable Boolean from column name |
GetNullableByte(int i, byte? defaultValue = null) | Retrieves a nullable Byte from column index |
GetNullableByte(string name, byte? defaultValue = null) | Retrieves a nullable Byte from column name |
GetNullableChar(int i, char? defaultValue = null) | Retrieves a nullable Char from column index |
GetNullableChar(string name, char? defaultValue = null) | Retrieves a nullable Char from column name |
GetNullableDateTime(int i, DateTime? defaultValue = null) | Retrieves a nullable DateTime from column index |
GetNullableDateTime(string name, DateTime? defaultValue = null) | Retrieves a nullable DateTime from column name |
GetNullableDecimal(int i, decimal? defaultValue = null) | Retrieves a nullable Decimal from column index |
GetNullableDecimal(string name, decimal? defaultValue = null) | Retrieves a nullable Decimal from column name |
GetNullableDouble(int i, double? defaultValue = null) | Retrieves a nullable Double from column index |
GetNullableDouble(string name, double? defaultValue = null) | Retrieves a nullable Double from column name |
GetNullableFloat(int i, float? defaultValue = null) | Retrieves a nullable Float from column index |
GetNullableFloat(string name, float? defaultValue = null) | Retrieves a nullable Float from column name |
GetNullableGuid(int i, Guid? defaultValue = null) | Retrieves a nullable Guid from column index |
GetNullableGuid(string name, Guid? defaultValue = null) | Retrieves a nullable Guid from column name |
GetNullableInt16(int i, short? defaultValue = null) | Retrieves a nullable Int16 from column index |
GetNullableInt16(string name, short? defaultValue = null) | Retrieves a nullable Int16 from column name |
GetNullableInt32(int i, int? defaultValue = null) | Retrieves a nullable Int32 from column index |
GetNullableInt32(string name, int? defaultValue = null) | Retrieves a nullable Int32 from column name |
GetNullableInt64(int i, long? defaultValue = null) | Retrieves a nullable Int64 from column index |
GetNullableInt64(string name, long? defaultValue = null) | Retrieves a nullable Int64 from column name |
GetNullableString(int i, string? defaultValue = null) | Retrieves a nullable String from column index |
GetNullableString(string name, string? defaultValue = null) | Retrieves a nullable String from column name |
GetNullableValue(int i, object? defaultValue = null) | Retrieves a nullable Object from column index |
GetNullableValue(string name, object? defaultValue = null) | Retrieves a nullable Object from column name |
| Method | Description |
|---|---|
GetFieldValue<T>(string name) | Gets the value of the specified column as the requested type |
GetFieldValueAsync<T>(string name, CancellationToken cancellationToken = default) | Asynchronously gets the value of the specified column as the requested type |
GetFieldValueOrDefault<T>(int ordinal, T defaultValue = default!) | Gets the value of the specified column or the default value if null |
GetFieldValueOrDefault<T>(string name, T defaultValue = default!) | Gets the value of the specified column or the default value if null |
GetFieldValueOrDefaultAsync<T>(int ordinal, T defaultValue = default!, CancellationToken cancellationToken = default) | Asynchronously gets the value of the specified column or the default value if null |
GetFieldValueOrDefaultAsync<T>(string name, T defaultValue = default!, CancellationToken cancellationToken = default) | Asynchronously gets the value of the specified column or the default value if null |
Contributions are welcome! Please feel free to submit issues, feature requests, or pull requests.
This package is part of the NetEvolve ecosystem of .NET extensions and utilities. Check out other packages in the NetEvolve family for additional functionality.
Made with ❤️ by the NetEvolve Team