我目前正在将我 6 岁的 C# 应用程序转换为 .NET Core v3 和 EF Core(也使用 Blazor)。除了分片部分外,大部分都在工作。
我们的应用程序为每个客户创建一个新数据库。我们或多或少地使用了这个代码:https
://docs.microsoft.com/en-us/azure/sql-database/sql-database-elastic-scale-use-entity-framework-applications-visual-studio
I '我现在正试图将其转换为 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 中不存在这种方式。TenantContext.Database.EnsureCreated();
我想我可以在某处使用它来简化它。但我不知道如何修改方法、删除哪些、更改哪些(以及如何)。
当然,我一直在寻找使用分片和 EF Core 的示例,但找不到。这里有没有人以前在 EF Core 中做过这个并且愿意分享?
当我创建一个新客户端时,我正在专门寻找要放入什么startup.cs
以及如何创建一个新的分片/数据库。