Each database providers have different data types that would map to the same C# types (Guid / DateTime)
I want to configure the column types depending on the database provider used.
For example:
public class MyClass
{
public Guid Id { get; set; }
public DateTime CreatedOn { get; set; }
}
If Sql Server is used
DateTime
as datetime2(0)
If MySql Server is used
DateTime
as TIMESTAMP
Guid
as CHAR(36)
So, I'm looking for code similar to below:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
if(IsSqlServer)
{
modelBuilder.Entity<MyClass>()
.Property(e => e.CreatedOn)
.HasColumnType("datetime2(0)")
;
}
else if(IsMySqlServer)
{
modelBuilder.Entity<MyClass>()
.Property(e => e.CreatedOn)
.HasColumnType("TIMESTAMP")
;
modelBuilder.Entity<MyClass>()
.Property(e => e.Id)
.HasColumnType("CHAR(36)")
;
}
}
Is it possible to do so in EF Core? (Latest stable 3.1 as time of writing)
As per the default conventions in EF 6 and EF Core, it creates a column in a db table with the same name and order as the property names. Column Attribute:
Each entity type in your model has a set of properties, which EF Core will read and write from the database. If you're using a relational database, entity properties map to table columns. By convention, all public properties with a getter and a setter will be included in the model.
Entity Framework Core can access many different databases through plug-in libraries called database providers. EF Core providers are built by a variety of sources. Not all providers are maintained as part of the Entity Framework Core Project.
Most database providers for EF Core are distributed as NuGet packages, and can be installed as follows: Once installed, you will configure the provider in your DbContext, either in the OnConfiguring method or in the AddDbContext method if you are using a dependency injection container.
Within the DbContext, you can use this.Database.ProviderName
if (this.Database.ProviderName == "Microsoft.EntityFrameworkCore.SqlServer")
{
modelBuilder.Entity<MyClass>()
.Property(e => e.CreatedOn)
.HasColumnType("datetime2(0)")
;
}
Some providers also include extension methods to help with that
if (this.Database.IsSqlServer())
{
modelBuilder.Entity<MyClass>()
.Property(e => e.CreatedOn)
.HasColumnType("datetime2(0)")
;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With