【发布时间】:2020-12-25 20:09:35
【问题描述】:
我正在使用 Azure Cosmos DB (SQL API) 创建一个 REST API 作为我使用 Entity Framework Core 的数据库。当我像这样配置服务时,我将 DbContext 添加为依赖项:
services.AddDbContext<MyContext>(
options => options.UseCosmos(CosmosDbEndpoint, CosmosDbAuthKey, CosmosDbName, cosmosOptionsAction => cosmosOptionsAction.ConnectionMode(ConnectionMode.Direct)));
DBContext 本身以标准方式实现
public class PharmacyExpressContext : IdentityDbContext<User>
{
protected PharmacyExpressContext()
{
Database.EnsureCreated();
}
public PharmacyExpressContext (DbContextOptions<PharmacyExpressContext> options): base(options)
{
Database.EnsureCreated();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{...
}
//DbSets here
....
}
当我检查日志时,我注意到每次调用我的 API 时,Entity Framework 都会重新初始化,这会被记录:
2020-09-07T11:28:28.790492961Z: [INFO] Entity Framework Core 3.1.7 initialized 'MyContext' using provider 'Microsoft.EntityFrameworkCore.Cosmos' with options: ServiceEndPoint=https:[Redacted] Database=[Redacted]
暗示连接不是持久的。然后经过几个请求,我会得到
2020-09-07T11:37:49.899167416Z: [INFO] CosmosException;StatusCode=TooManyRequests;SubStatusCode=3200;ActivityId=176a9a48-9e57-4c17-9135-8ac776406c81;RequestCharge=0;Message=Response status code does not indicate success: 429 Substatus: 3200 Reason: (Message: {"Errors":["Request rate is large. More Request Units may be needed, so no changes were made. Please retry this request later. Learn more: http://aka.ms/cosmosdb-error-429"]}
我尝试从 Azure 增加我的数据库上的 RU,但这没有帮助。我经历的其他实现创建了一个完成 CRUD 的客户端,但不包括 EF Core。我不确定我错过了什么。
编辑 不确定这是否相关,但我还在同一个数据库上创建了一个分区存储来存储用户状态和对话状态。
var storage = new CosmosDbPartitionedStorage(
new CosmosDbPartitionedStorageOptions
{
CosmosDbEndpoint = CosmosDbEndpoint,
AuthKey = CosmosDbAuthKey,
DatabaseId = CosmosDbName,
ContainerId = CosmosContainerId,
CompatibilityMode = false,
});
var conversationState = new ConversationState(storage);
services.AddSingleton(conversationState);
var userState = new UserState(storage);
services.AddSingleton(userState);
【问题讨论】:
-
在 OnConfiguring() 中添加
options.ExecutionStrategy(d => new CosmosExecutionStrategy(d));以处理 CosmosDB 中的 429 个请求。让我知道这是否有效。 -
谢谢...让我试试这个。
-
能否请您检查一下数据库是否已经创建?如果它已创建,请删除
Database.EnsureCreated(),因为它会尝试检查数据库并在每个请求上创建模型,这不推荐并且会产生性能问题。 -
@HarshitaSingh-MSFT 没用。
-
请参考docs.microsoft.com/en-us/azure/cosmos-db/…。我们可以通过在
CosmosClientOptions实例上设置RetryOptions来更改默认重试次数来修复它。
标签: c# asp.net-core entity-framework-core azure-cosmosdb