Reputation: 16440
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)
Upvotes: 7
Views: 2426
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