我目前正在将我的6年C#应用程序转换为.NET Core v3和EF Core(还使用Blazor)。
它的大部分功能都能正常工作,除了Sharding部分。
我们的应用程序为每个客户端创建一个新的数据库。我们使用的代码大致如下:https://learn.microsoft.com/en-us/azure/sql-database/sql-database-elastic-scale-use-entity-framework-applications-visual-studio
我现在正在尝试将其转换为EF Core,但卡在这一部分:
上述代码无法编译,因为在EF Core中不存在Database对象。我认为可以使用
当然,我一直在搜索使用分片和EF Core的示例,但没有找到。这里有人在EF Core中做过这个并愿意分享吗?
我特别想知道在
// C'tor to deploy schema and migrations to a new shard
protected internal TenantContext(string connectionString)
: base(SetInitializerForConnection(connectionString))
{
}
// Only static methods are allowed in calls into base class c'tors
private static string SetInitializerForConnection(string connnectionString)
{
// We want existence checks so that the schema can get deployed
Database.SetInitializer<TenantContext<T>>(new CreateDatabaseIfNotExists<TenantContext<T>>());
return connnectionString;
}
// C'tor for data dependent routing. This call will open a validated connection routed to the proper
// shard by the shard map manager. Note that the base class c'tor call will fail for an open connection
// if migrations need to be done and SQL credentials are used. This is the reason for the
// separation of c'tors into the DDR case (this c'tor) and the internal c'tor for new shards.
public TenantContext(ShardMap shardMap, T shardingKey, string connectionStr)
: base(CreateDDRConnection(shardMap, shardingKey, connectionStr), true /* contextOwnsConnection */)
{
}
// Only static methods are allowed in calls into base class c'tors
private static DbConnection CreateDDRConnection(ShardMap shardMap, T shardingKey, string connectionStr)
{
// No initialization
Database.SetInitializer<TenantContext<T>>(null);
// Ask shard map to broker a validated connection for the given key
var conn = shardMap.OpenConnectionForKey<T>(shardingKey, connectionStr, ConnectionOptions.Validate);
return conn;
}
上述代码无法编译,因为在EF Core中不存在Database对象。我认为可以使用
TenantContext.Database.EnsureCreated();
来简化它。但我不知道如何修改方法,哪些需要删除,哪些需要更改(以及如何更改)。当然,我一直在搜索使用分片和EF Core的示例,但没有找到。这里有人在EF Core中做过这个并愿意分享吗?
我特别想知道在
startup.cs
中要放什么,以及在创建新客户端时如何创建新的分片/数据库。