You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断当前使用的是SQL Server还是SQLite数据库提供程序?

在Entity Framework Core中根据数据库提供程序做条件实体配置

你可以在IEntityTypeConfiguration<T>的实现类里,通过EntityTypeBuilder的元数据获取当前数据库提供程序的信息,进而实现条件化配置。

具体实现方式

  1. 在配置类的Configure方法中,通过entity.Metadata.GetServiceProvider()获取服务提供器,再从中提取数据库提供程序的名称。
  2. 使用EF Core内置的提供程序名称常量(避免硬编码字符串)判断当前环境是SQL Server还是SQLite,分别执行对应配置逻辑。

代码示例

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.SqlServer.Infrastructure;
using Microsoft.EntityFrameworkCore.Sqlite.Infrastructure;

public class MyEntityConfiguration : IEntityTypeConfiguration<MyEntity>
{
    public void Configure(EntityTypeBuilder<MyEntity> entity)
    {
        // 通用实体配置
        entity.HasKey(e => e.Id);
        entity.Property(e => e.Name).IsRequired().HasMaxLength(100);

        // 获取当前数据库提供程序信息
        var relationalExtension = entity.Metadata.GetServiceProvider()
            .GetRequiredService<IDbContextOptions>()
            .FindExtension<RelationalOptionsExtension>();
        
        var providerName = relationalExtension?.ProviderName;

        // SQL Server专属配置:RowVersion并发令牌
        if (providerName == SqlServerOptionsExtension.ProviderName)
        {
            entity.Property(e => e.RowVersion)
                  .IsRequired(true)
                  .IsRowVersion()
                  .IsConcurrencyToken();
        }
        // SQLite兼容配置(SQLite原生不支持RowVersion,按需调整)
        else if (providerName == SqliteOptionsExtension.ProviderName)
        {
            entity.Property(e => e.RowVersion)
                  .IsRequired(true)
                  .HasColumnType("BLOB")
                  .HasDefaultValueSql("CURRENT_TIMESTAMP");
        }
    }
}

关键说明

  • 使用SqlServerOptionsExtension.ProviderName和SqliteOptionsExtension.ProviderName内置常量,比直接写字符串更安全,避免拼写错误。
  • SQLite不支持SQL Server的ROWVERSION类型,需要替换为兼容的配置逻辑,比如用BLOB类型配合默认值,或根据业务需求调整并发控制方案。
  • 确保项目已安装对应EF Core提供程序包:Microsoft.EntityFrameworkCore.SqlServer和Microsoft.EntityFrameworkCore.Sqlite。

内容的提问来源于stack exchange,提问作者user20326571

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 07:57:51