How to call store procedures with async and await in C#

2.2k views Asked by At

I am using visual studio 2015 community version, and MVC 5, entity framework 6. I am just learned how to use async and await for making asynchronous call.

Now in my project I have only CRUD operations and for all operations I have written store procedures, I dont have more bussiness logic in my API's except calling store procedures. So I am using async and await for calling store procedure.

But doing that, I am getting error,

'int' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)

My code is,

 [HttpPost]
        public async Task<IHttpActionResult> AddContactEmails(Contacts data)
        {
            using (JodoDataEntities DB = new JodoDataEntities())
            {
                int Result = await DB.AddContacts(data.userId, data.data);
                return Ok();
            }
        }

My store procedure is very simple, I am returning anything from it, still EF taking it as int return type.

ALTER PROCEDURE [dbo].[AddContacts]
    @userId nvarchar(128),
    @contacts nvarchar(MAX)
AS
BEGIN
    SET NOCOUNT ON;
    if not exists(select top 1 * from Contacts where userId = @userId)
    begin
        insert into Contacts (userId, contacts) VALUES (@userId, @contacts)
    end
END

EF code (Generated automatically),

 public virtual int AddContacts(string userId, string contacts)
        {
            var userIdParameter = userId != null ?
                new ObjectParameter("userId", userId) :
                new ObjectParameter("userId", typeof(string));

            var contactsParameter = contacts != null ?
                new ObjectParameter("contacts", contacts) :
                new ObjectParameter("contacts", typeof(string));

            return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("AddContacts", userIdParameter, contactsParameter);
        }

1). Why I am getting this error while calling method ?

2). where do I need to change to make it work ?

3). So I really need to use async and await when I have only SP calls in my API's ?

1

There are 1 answers

8
David On

If this returns a Task<int>:

DB.AddContacts(...);

Then this simply returns an int:

await DB.AddContacts(...);

So the Result variable should be of type int, not Task<int>.


Edit: I just noticed the definition for AddContacts() in your question. It's not an async method, so it can't be awaited. There are no async operations in your code. Just remove the async and await attempts entirely, this is synchronous code...

int Result = DB.AddContacts(...);

As an aside, this is a bad idea:

catch (Exception ex)
{
    throw ex;
}

It's basically throwing away useful debugging information. Just remove the try/catch construct entirely and let the exception be thrown by the operation which originally throws it.