Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a stored procedure and forget about it using C# and Entity Framework?

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?

like image 308
Junior Avatar asked Feb 14 '17 00:02

Junior


1 Answers

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.

like image 93
Lostblue Avatar answered Nov 01 '22 21:11

Lostblue