EF Core 2.0 provider specific model configuration

孤街醉人 提交于 2019-12-24 01:53:58

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/46088952/ef-core-2-0-provider-specific-model-configuration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!