Search code examples
entity-framework-coreef-model-builder

EF Core 2.0 provider specific model configuration


I am trying to upgrade an EF Core 1.x project to 2.0. In 1.x I was taking advantage of provider-specific extension methods (e.g. ForSqlServerHasDefaultValueSql/ForSqliteHasDefaultValueSql or ForSqlServerHasColumnType) but these seem to have been removed in 2.0.

Since each provider has its own flavor of SQL and capabilities, I need to be able to use slightly different setups or SQL strings per provider in OnModelCreating. For example to set a default value I might have:

modelBuilder<Foo>(b =>
{
    b.Property(x => x.CreateDate)
        .IsRequired()
        .ForSqlServerHasDefaultValueSql("getutcdate()")
        .ForSqliteHasDefaultValueSql("CURRENT_TIMESTAMP");
}

How is this done in 2.0?


Solution

  • I couldn't find anything in the documentation (yet) but digging deep into the source, there is a comment in the logs of commit 747c86556b2a21526973d462626e299b9bde7b91:

    Remove ForSqlServer... ForSqlite... methods for relational concepts

    Part of #7166

    Code can instead use

    if (Database.IsSqlServer())
    {
        modelBuilder.HasColumnName("MySqlServerName");
    }
    

    Therefore the snippet in the question would translate to:

    modelBuilder<Foo>(b =>
    {
        b.Property(x => x.CreateDate)
            .IsRequired();
    
        if (Database.IsSqlServer())
            b.Property(x => x.CreateDate).HasDefaultValueSql("getutcdate()");
    
        if (Database.IsSqlite())
            b.Property(x => x.CreateDate).HasDefaultValueSql("CURRENT_TIMESTAMP");
    }
    

    Kudos to @IvanStoev for pointing me to the 1.x to 2.0 upgrade documentation. Somehow my Google-fu was failing me today. On this page it clearly shows what to do:

    Instead of using methods like ForSqlServerToTable, extension methods are now available to write conditional code based on the current provider in use. For example:

    modelBuilder.Entity<User>().ToTable(
        Database.IsSqlServer() ? "SqlServerName" : "OtherName");