Rick Su
Rick Su

Reputation: 16440

EF Core - How to Configure Column Type depending on the Database Provider used

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

If MySql Server is used

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)

Upvotes: 7

Views: 2426

Answers (1)

ESG
ESG

Reputation: 9425

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)")
        ;
}

Upvotes: 6

Related Questions