Type Mapping
This is a feature that would allow you to map the .NET CLR type into its equivalent database type.
Below are the important attributes per data provider.
Attribute | RDBMS | Data Provider |
---|---|---|
SqlDbTypeAttribute | SQL Server | Microsoft.Data.SqlClient |
MySqlDbTypeAttribute | MySQL | MySql.Data, MySqlConnector |
NpgsqlDbTypeAttribute | PostgreSQL | Npgsql |
SqliteTypeAttribute | SQLite | Microsoft.Data.Sqlite |
Mapping a .NET CLR type
To map a .NET CLR type, simply use the TypeMapper class.
TypeMapper.Map(typeof(DateTime), DbType.DateTime2);
Or via FluentMapper class.
FluentMapper
.Type<DateTime>
.DbType(DbType.DateTime2);
Mapping a Specific Property
To map a specific class property, simply use the TypeMap attribute.
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
[TypeMap(DbType.DateTime2)] // Mapping this to 'DateTime2'
public DateTime DateOfBirth { get; set; }
public DateTime DateInsertedUtc { get; set; }
}
SQL Server
In SQL Server, you can also map to a specific System.Data.SqlDbType SqlDbTypeAttribute.
public class Person
{
public int Id { get; set; }
[SqlDbType(SqlDbType.NVarChar)] // Mapping this to 'NVarChar'
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
public DateTime DateInsertedUtc { get; set; }
}
MySQL
In MySQL, you can also map to a specific MySql.Data.MySqlClient.MySqlDbType using the MySqlDbTypeAttribute.
public class Person
{
public int Id { get; set; }
[MySqlDbType(MySqlDbType.VarChar)] // Mapping this to a 'VarChar'
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
public DateTime DateInsertedUtc { get; set; }
}
PostgreSQL
In PostgreSQL, you can also map to a specific NpgsqlTypes.NpgsqlDbType using the NpgsqlDbTypeAttribute.
public class Person
{
public int Id { get; set; }
[NpgsqlDbType(NpgsqlDbType.Text)] // Mapping this to a 'Text'
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
public DateTime DateInsertedUtc { get; set; }
}
SQLite
In PostgreSQL, you can also map to a specific Microsoft.Data.Sqlite.SqliteType using the SqliteTypeAttribute.
public class Person
{
public int Id { get; set; }
[SqliteType(SqliteType.Text)] // Mapping this to a 'Text'
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
public DateTime DateInsertedUtc { get; set; }
}