Link Search Menu Expand Document

Converter


The main converter class for the library. It exposes mutable properties that affect how the library converts data when reading from or writing to the database.

Properties

NameDescription
ConversionTypeThe conversion type used when converting a DbDataReader into .NET CLR types. Defaults to ConversionType.Default.
EnumDefaultDatabaseTypeThe default database type for enumerations when used as parameters in non-entity-based operations (ExecuteScalar, ExecuteNonQuery, ExecuteReader).

Deprecated

Methods

NameDescription
DbNullToNullConverts DBNull.Value to null.
ToTypeReturns the value as-is if the type matches the target; otherwise converts it.

Setting to Automatic Conversion

To enable automatic conversion between .NET CLR types and database types, set ConversionType to Automatic.

Converter.ConversionType = ConversionType.Automatic;

Deprecated

See the ConversionType enumeration for details.

When to use the Enum Default Database Type?

Use this setting to override the default enumeration conversion behavior. By default, the library converts enumerations to DbType.String for non-model-based operations.

Given the following enumerations:

public enum CustomerType
{
    Direct,
    Indirect
}

public enum CustomerStatus
{
    Active,
    InActive
}

The following forces all enumeration properties to be converted to DbType.Int32:

// Set the Default Conversion for Enums
Converter.EnumDefaultDatabaseType = DbType.Int32;

// Non-Model Based Method Call
using (var connection = new SqlConnection(connectionString))
{
    var sql = "INSERT INTO [dbo].[Customer] (Name, CustomerType, CustomerStatus) " +
        "VALUES (@Name, @CustomerType, @CustomerStatus); " +
        "SELECT SCOPE_IDENTITY();";
    var param = new
    {
        Name = "John Doe",
        CutomerType = CustomerType.Direct,
        CustomerStatus = CustomerStatus.Active
    };
    var id = connection.ExecuteScalar<long>(sql, param);
}

This setting does not apply to model-based operations, where the library uses the database schema definition. It also does not override mappings configured at the property or type level.

DbNull Conversion

Use DbNullToNull to convert a DbDataReader value to null when it is DBNull.Value.

using (var connection = new SqlConnection(connectionString))
{
    using (var reader = connection.ExecuteReader())
    {
        var name = Converter.DbNullToNull(reader["Name"]);
    }
}

Converting to Specific Type

Use ToType to convert a value to a specific type. If the types match, the value is returned directly; otherwise, System.ChangeType is used.

var value = "12345";
var converted = Converter.ToType<int>(value);