本文介绍了在我的CosmosDb中创建存储过程,如何通过我的.net wep API(连接到我的cosmosDb)访问它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经将服务器端存储过程命名为sample(这是默认存储过程),如何在.net Web API中调用它?

I've made server side stored procedure named sample ( it's the default stored procedure) how can I call it inside my .net web API ?

推荐答案

参考: https://github.com/Azure/azure-cosmos-dotnet-v3/blob/master/Microsoft.Azure.Cosmos.Samples/Usage/ServerSideScripts/Program.cs

使用 V3 .NET SDK ,您可以像这样执行存储过程:

Using the V3 .NET SDK, you can execute your stored procedure like so:

CosmosClient client = new CosmosClient("connection string");
Container container = client.GetContainer("YourDbName", "YourContainerName");
StoredProcedureExecuteResponse response = await container.Scripts.ExecuteStoredProcedureAsync(
                "sample", // your stored procedure name
                new PartitionKey("Partition Key you want to run it on"),
                new dynamic[] { "Your First parameter", "Your second parameter" });

// If your stored procedure returns some information, you can use the Type of the data you expect. For example, if you expect a string
StoredProcedureExecuteResponse<string> responseWithData = await container.Scripts.ExecuteStoredProcedureAsync<string>(
                "sample", // your stored procedure name
                new PartitionKey("Partition Key you want to run it on"),
                new dynamic[] { "Your First parameter", "Your second parameter" });

如果要创建Web API,请确保维护 Singleton实例,通常将其注册为Startup的一部分.不要为每个操作创建CosmosClient的新实例.

If you are creating a Web API, please make sure you maintain a Singleton instance of the CosmosClient, often registering it as part of the Startup. Do not create new instances of the CosmosClient for each operation.

这意味着,在Startup.cs中注册了服务的位置rel ="nofollow noreferrer"> DI容器,您可以在其中添加它:

This means that, in your Startup.cs where services are being registered in the DI container, you can add it there:

public void ConfigureServices(IServiceCollection services)
{
    // ... other code you might already have
    CosmosClient client = new CosmosClient("connection string");
    services.AddSingleton(client);
}

并在控制器中注入CosmosClient实例:

And inject the CosmosClient instance in your Controller:

public class MyController
{
    private readonly CosmosClient cosmosClient;
    public MyController(CosmosClient cosmosClient)
    {
        this.cosmosClient = cosmosClient;
    }

    public async Task<IActionResult> MyMethod()
    {
        // execute the stored procedure or use this.cosmosClient

    }
}

完整的Web API示例: https://github.com/Azure-Samples/cosmos-dotnet-core-todo-app

Full Web API sample: https://github.com/Azure-Samples/cosmos-dotnet-core-todo-app

这篇关于在我的CosmosDb中创建存储过程,如何通过我的.net wep API(连接到我的cosmosDb)访问它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 18:19