2

We are moving to Entity Framework, however we have a large number of stored procedures. If our Web API uses an async/await pattern all the way to the stored procedure call, how do I handle the call? Can I/should I make it async as well?

I have a db context and I can call my stored procedure Foo synchronously. This works however the calling code is all wrapped with async/await keywords. The stored procedure in question is also a Select and not an Insert/Update/Delete. I cannot use ToListAsync() on the context.Foo call, if I try

context.Database.ExecutSQLCommandAsync() 

I only get a Task<int> back and not my object. Is there a best practice here?

public async Task<List<FooData>> GetFoo(string param)
{
    List<FooData> dataList = new List<FooData>();

    using(dbEntities context = new dbEntities(connectionstring))
    {
        //  this runs as expected
        var result =  context.Foo(param).ToList();

        if(result != null)
        {
            result.ForEach(delegate(Foo_Result item)
                               {
                                   //  load object
                               });
        }
    }

    return dataList;
}

I suppose I could do this

var result = await Task.Run(()=> context.Foo(param).ToList());

but this is an Entity Framework db call and not an CPU intensive process. Is there a best practice to follow here? Thanks

2
  • 1
    See this answer stackoverflow.com/a/24454001/2030565 Commented Sep 13, 2019 at 18:13
  • It doesn't seem to work with a directly invoked stored proc. Commented Sep 16, 2019 at 18:38

1 Answer 1

4

If you want a result set, then you'll need Database.SqlQuery.

public class MyDbContext : DbContext
{
    public async Task<IList<Foo>> GetFooAsync(int n)
    {
       var query = base.Database.SqlQuery<Foo>("exec fooStoredProc @n",
           new SqlParameter("@n", n));
       return await query.ToListAsync();
    }
}

With usage

public async Task Exec()
{
    MyDbContext db = new MyDbContext();
    var foos = await db.GetFooAsync(1);
}

This assumes your stored proc returns fields that match up to your Foo class.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.