Asynchronous Controller of Web API 2 With Entity Framework 6: Get() Method

We know that both are the latest release of the Microsoft stack. It will be a nice combination if we combine Entity Framework 6 with the Web API in application development. Anyway this article explains the Get() method to get data from the Web API asynchronously.

Please check whether or not you are using Entity Framework 6 or higher because Entity Framework 6 supports DB operations in Asynchronously.

In our example we will consume data from the .NET client, if necessary you can implement a JavaScript client too. So, let's pick the Web API 2 template and create this simple controller.

The ResponseType attribute will define the response type of the controller. Since we will return a company record from the database (very soon we will see the table). Since the controller is asynchronous in nature, we are returning a Task and we are using the await keyword to fetch data from the Entity Framework.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Http;

using System.Web.Mvc;

using System.Threading.Tasks;

using System.Web.Http.Description;

namespace WebAPI.Controllers

{

    public class AsyncPersonController : ApiController

    {

        [ResponseType(typeof(company))]

        public async Task<IHttpActionResult> Get(int Id)

        {

            using (var ctx = new efDBEntities())

            {

                company com = await ctx.company.FindAsync(Id);

                if (com != null)

                    return Ok(com);

                else

                    return NotFound();

            }

        }

    }

}

If the company is not null then it will return Ok, a success message from the Controller otherwise it will return NotFound.

Here is our table information from where the Entity Framework will fetch the data.

table

So, if we pass 1 as the id then it will return the first record from the table. Let's create a .NET client to consume data from the Web API. Have a look at the following code.
 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using ClassLibrary;

using System.Threading;

using System.Net.Http;

using System.Net.Http.Headers;

using System.Net.Http.Formatting;

using Newtonsoft.Json;

 

namespace ConsoleAPP

{

    class Program

    {

        static void Main(string[] args)

        {

            using (var client = new HttpClient())

            {

                client.BaseAddress = new Uri("http://localhost:1565/");

                var response = client.GetAsync("api/AsyncPerson/1").Result;

                var data = response.Content;

 

                if (response.IsSuccessStatusCode)

                {

                    Task<string> d = data.ReadAsStringAsync();

                    Console.Write(d.Result.ToString());

                }               

                Console.ReadLine();

            }

        }

    }

}

And it will print the first record from the table.

record from the table

If you want to read all the data from the DB, then the scenario is changed a little, there is not an asynchronous method that can fetch all the data asynchronously . Here is one synchronous solution but since the function is decorated with the “async” keyword, we can call it asynchronously.
 

public async Task<IHttpActionResult> GetAll()

{

    using (var ctx = new efDBEntities())

    {

        List<company> com = ctx.company.ToList();

         if (com != null)

             return Ok(com);

        else

            return NotFound();

    }

}

Here the return string is in JSON format.

JSON format

Finally

This article showed how to read data from the Web API asynchronously. In a future article we will do the Put() , post() and delete operations asynchronously.

Up Next
    Ebook Download
    View all
    Learn
    View all