Created Stored procedures in my CosmosDb, how can I access them through my .net wep API (which is connected to my cosmosDb) [closed]

有些话、适合烂在心里 提交于 2019-12-25 17:38:13

问题


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 ?


回答1:


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

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" });

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.

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);
}

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

    }
}

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



来源:https://stackoverflow.com/questions/58766288/created-stored-procedures-in-my-cosmosdb-how-can-i-access-them-through-my-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!