在我们的 ASP.NET Core 和 EF Core 系统中,我们为系统的不同部分使用不同的数据库。我需要能够在运行时判断正在使用哪个数据库提供程序,因为有些东西需要考虑到这一点。
在启动过程中,SQL Server 是这样的:
services.AddDbContext<MyContext>(
options => options.UseSqlServer(config.GetConnectionString("DefaultConnection"))
);
或者 SQLite 的这个:
services.AddDbContext<MyContext>(
options => options.UseSqlite(config.GetConnectionString("DefaultConnection"))
);
关键是关于正在使用哪个数据库的知识包含在系统中的某处。
在系统中的任意点,我如何确定我正在使用哪个数据库?我可以访问 MyContext
。里面有什么东西可以揭示这些信息吗?
最佳答案
我在我的项目中使用了 3 个数据库提供商。
- Npgsql.EntityFrameworkCore.PostgreSQL
- Microsoft.EntityFrameworkCore.SqlServer
- Pomelo.EntityFrameworkCore.MySql
在我的项目中没有使用。 更新。 2020 年 6 月 17 日。我注意到 Oracle Provider 有一个扩展方法 IsOracle。
- Oracle.EntityFrameworkCore Oracle.EntityFrameworkCore 3.19.0-beta1
在您的客户端项目中,可以从 Nuget 包管理器或 CLI 添加任何这些引用。
引用包含以下扩展方法。
Boolean isPostgreSQL = context.Database.IsNpgsql();
Boolean isSqlServer = context.Database.IsSqlServer();
Boolean isMySql = context.Database.IsMySql();
Boolean isOracle= context.Database.IsOracle();
示例 1
public static EntityTypeBuilder<TEntity> ToTable<TEntity>(this EntityTypeBuilder<TEntity> builder, string schema, DatabaseFacade database) where TEntity : class
{
switch(database)
{
case DatabaseFacade db when db.IsMySql():
builder.ToTable($"{schema}.{typeof(TEntity).Name}");
break;
case DatabaseFacade db when db.IsSqlServer() | db.IsNpgsql():
builder.ToTable(typeof(TEntity).Name, schema);
break;
default:
throw new NotImplementedException("Unknown database provider.");
}
return builder;
}
示例 2
private static string GetEffectiveConstraintName(string name, DatabaseFacade database)
{
return database switch
{
DatabaseFacade db when db.IsSqlServer() => name,
DatabaseFacade db when db.IsNpgsql() => name.Length < DataAccessConstants.PostgreSqlIdentifierMaxLength ? name : name.Substring(0, DataAccessConstants.PostgreSqlIdentifierMaxLength),
DatabaseFacade db when db.IsMySql() => name.Length < DataAccessConstants.MySqlIdentifierMaxLength ? name : name.Substring(0, DataAccessConstants.MySqlIdentifierMaxLength),
_ => throw new NotImplementedException("Unknown database provider")
};
}
关于c# - 使用 EF Core 在运行时确定正在使用哪个数据库提供程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40621262/