I am using Entity Framework for an app that I wrote using ASP.NET MVC.
I need to be able to call a stored procedure and forget about it. I don't care about the result I just want to trigger it.
I tried to accomplish that by using a separate connection for calling the stored procedure using the ExecuteSqlCommandAsync
method. But the stored procedure does not seems to be getting fired.
Here is my async method
protected async Task ProcessRecords(DateTime loadedAt, string email)
{
try
{
using (var conn = new AppContext())
{
var result = conn.Database.ExecuteSqlCommandAsync("EXEC [DedecatedProcesses] @p0, @p1;", loadedAt, email);
await Task.WhenAll(result);
}
}
catch (Exception e)
{
// Do something with e.Message
}
}
Then from an action method with in a controller I call it like so
var loaded = ProcessRecords(DateTime.UtcNow, model.Email);
I do not get any error when I run my code but the procedure does not run.
When I execute the stored procedure using SSMS it runs with no problems.
How can I correctly call the stored procedure and forget about it?
Before answering your question, I want to point this out :
You create an async Task, if "correctly" used you would already have an async call. Something wrong beforehand?
Answer :
await
is a call that will not end your curent context by default. In this case you will wait ExecuteSqlCommandAsync
at the end of the try
.
You can explicitly remove this behaviour as follow :
protected async Task ProcessRecords(DateTime loadedAt, string email)
{
try
{
using (var conn = new AppContext())
{
await conn.Database.ExecuteSqlCommandAsync("DedecatedProcesses @p0, @p1;", loadedAt, email)
.ConfigureAwait(false);
}
}
catch (Exception e)
{
// Do something with e.Message
}
}
NB: There is no point to store your result here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With