I am trying to use my DbContext
with multiple providers. So far everything works okay, except when using HasDefaultValueSql()
.
What I am trying to do is to have a property AuditTimestamp
that has the current time when added (and saved) on the dbContext
. This can easily be done using something like this that works for the SQL Server provider
modelBuilder
.Entity(entityType.ClrType)
.Property(nameof(AuditBase.AuditTimestamp))
.HasDefaultValueSql("SYSUTCDATETIME()");
But when trying to use the same dbContext
with SqLite provider, it doesn't work since SYSUTCDATETIME
isn't a valid SQL function in SqLite.
Based on this question I tried to do
modelBuilder
.Entity(entityType.ClrType)
.Property(nameof(AuditBase.AuditTimestamp))
.HasDefaultValueSql(Database.IsSqlite() ? "DATETIME('now')" : "SYSUTCDATETIME()");
But it generates this in the migrations
b.Property<DateTime>("AuditTimestamp")
.ValueGeneratedOnAdd()
.HasDefaultValueSql("SYSUTCDATETIME()");
because I use a SQL Server connection string when generating the migrations. This implies that I need different sets of migrations based on what provider I use which shouldn't be the case.
Based on this question it is possible to have provider specific configurations in the migration files but the example is based on auto generated Id column and I don't know how to apply this to HasDefaultValueSql()
From here I found that this might work
HasDefaultValueSql("CURRENT_TIMESTAMP")
But I would like a more general solution for when you have two (or more) providers that don't share same SQL function names.
The providers I use is SQL Server for production and SqLite for unit testing. EF Core is version 2.2