azure - 无法使用 Microsoft.EntityFrameworkCore.Cosmos 连接到 Azure Cosmos Db 帐户 - 响应状态代码

标签 azure entity-framework-core azure-cosmosdb

CosmosDb 提供商正在发送此消息:

“响应状态代码不表示成功:503 子状态:0 原因:(请求失败,因为客户端无法与跨 1 个区域的 3 个端点建立连接。请检查客户端资源匮乏问题并验证连接客户端和服务器之间。”

在我的测试中,它有效(.net core 3.1):

Task.Run(async () =>
        {
            var endpoint = “test”;
            var masterKey = “test”;
            using (var client = new DocumentClient(new Uri(endpoint), masterKey))
            {
                //Insert new Document  
                Console.WriteLine("\r\n>>>>>>>>>>>>>>>> Creating Document <<<<<<<<<<<<<<<<<<<");
                dynamic candidato = new
                {
                    Id = 1,
                    Nome = "Test"
                };

                var document1 = await client.CreateDocumentAsync(
                    UriFactory.CreateDocumentCollectionUri("Test", "Test"),
                    candidato);

                Console.ReadKey();
            }

        }).Wait();

事实并非如此:

            Task.Run(async () =>
            {
                using (var context = new StudentsDbContext())
                {
                    context.Add(new FamilyContainer(2, "Test"));
                    await context.SaveChangesAsync();
                }

            }).Wait();

public class FamilyContainer
{
    public int Id { get; set; }
    public string Nome { get; set; }

    public FamilyContainer(int id, string nome)
    {
        Id = id;
        Nome = nome;
    }

}

public class StudentsDbContext : DbContext
{
    public DbSet<FamilyContainer> FamilyContainer { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseCosmos(
           "test",
           "test",
           "FamilyDatabase",
           options =>
           { }
         );
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<FamilyContainer>(x =>
        {
            x.ToContainer("FamilyContainer");
        });
    }
}

Packages

有人可以帮助我吗?谢谢

fail: Microsoft.EntityFrameworkCore.Update[10000] An exception occurred in the database while saving changes for context type '...'. Microsoft.EntityFrameworkCore.Storage.RetryLimitExceededException: Maximum number of retries (6) exceeded while executing database operations with 'CosmosExecutionStrategy'. See inner exception for the most recent failure. ---> Microsoft.Azure.Cosmos.CosmosException : Response status code does not indicate success: 503 Substatus: 0 Reason: (Microsoft.Azure.Documents.ServiceUnavailableException: Service is currently unavailable.ActivityId: 07fbf539-0d44-4e5a-89d0-cd46838ee605, {"RequestStartTimeUtc":"2020-02-21T16:34:09.1834993Z","RequestEndTimeUtc":"2020-02-21T16:34:41.3484203Z","RequestLatency":"00:00:32.1649210","IsCpuOverloaded":false,"NumberRegionsAttempted":1,"ResponseStatisticsList":[{"ResponseTime":"2020-02-21T16:34:11.5964152Z","ResourceType":2,"OperationType":0,"StoreResult":"StorePhysicalAddress: rntbd:.../, LSN: -1, GlobalCommittedLsn: -1, PartitionKeyRangeId: , IsValid: True, StatusCode: 410, SubStatusCode: 0, RequestCharge: 0, ItemLSN: -1, SessionToken: , UsingLocalLSN: False, TransportException: A client transport error occurred: Failed to connect to the remote endpoint. (Time: 2020-02-21T16:34:11.5298608Z, activity ID: 07fbf539-0d44-4e5a-89d0-cd46838ee605, error code: ConnectFailed [0x0005], base error: socket error ConnectionRefused [0x0000274D]... --- End of inner exception stack trace ---

最佳答案

我遇到了同样的问题。

对我有用的是在初始化CosmosClient时将ConnectionMode更改为ConnectionMode.Gateway,如下所示:

var options = new CosmosClientOptions() { ConnectionMode = ConnectionMode.Gateway };
var client = new CosmosClient(endpoint, key, options); 

更多详情请引用:

https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.cosmos.cosmosclientoptions?view=azure-dotnet

https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.cosmos.connectionmode?view=azure-dotnet

关于azure - 无法使用 Microsoft.EntityFrameworkCore.Cosmos 连接到 Azure Cosmos Db 帐户 - 响应状态代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60329059/

相关文章:

azure - 使用 azure b2c、MFA 和 REST API 时如何重置 MFA 并获取新的 QR

使用连接字符串时,Azure 函数使用者收到 401

c# - EF Core 3.1 到 5 更新 -> IEntityType.GetTableName

sql - 如何根据 ComosDb 中聚合函数的结果对查询结果进行排序?

c# - 在 Azure 中使用特定于时间的计时器

linux - 需要将 AWS NFS 挂载移动到 Azure

.net-core - 未找到 .Net Core v.1.1.0

c# - EF Core 有条件地启用延迟加载

c# - 如何使用 C# 更新 Azure CosmosDB 中的文档

azure - CosmosDB 集合中的更改是否会触发每个分区相同的 Azure 函数实例?