问题
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