Parthiban
Parthiban

Reputation: 101

How to make async and await method in asp.net MVC with Web api2


I’m newly to the ASP.NET MVC with Web API 2 and I created async and await method by using asp.net MVC with Web API 2 which is going to be store into the SQL DB. When I try to call my repository method in the API Controller I got an error cannot await ”system.collections.generic.list”. If anybody has idea about it kindly let me know.
Note:- I don’t want to use entity framework instead I want to store data through stored procedure.

Model:

namespace AsyncMVCWEBAPI.Models
{
    public class Product
    {
        public string Name { get; set; }
        public double Price { get; set; }
        public string Category { get; set; }
    }
}

API Controller:

public static async Task<Product> GetProduct()
{
    return await GetAllProduct(); // Here i'm getting an error can not await "system.collections.generic.list"
}

Repository:

public static IEnumerable<Product> GetAllProduct()
{           
    using (SqlConnection con = new SqlConnection(connectionString))
    {
        if (con.State == ConnectionState.Closed)
            con.Open();
        List<Product> students = new List<Product>();
        SqlCommand cmd = new SqlCommand("spGetAllStudentDetails", con);
        cmd.CommandType = CommandType.StoredProcedure;

        SqlDataReader rdr = cmd.ExecuteReader();
        while (rdr.Read())
        {
            Product product = new Product();
            product.Price = Convert.ToInt32(rdr["Price"]);
            product.Name = rdr["Name"].ToString();
            product.Category = rdr["Category"].ToString();

            students.Add(product);

        }
        return students;
    }           
}

enter image description here

Upvotes: 1

Views: 3763

Answers (2)

peco
peco

Reputation: 4000

As the previous answer said you have to change your signature to:

public static async Task<IEnumerable<Product>> GetAllProduct()

If you want to skip the ADO.NET boilerplate stuff, you can instead use Dapper (https://github.com/StackExchange/dapper-dot-net) to simplify the code:

public static async Task<IEnumerable<Product>> GetAllProduct()
{
    using (var con = new SqlConnection(connectionString))
    {
        await con.OpenAsync();
        return await con.QueryAsync<Product>("spGetAllStudentDetails", commandType: CommandType.StoredProcedure);
    }
}

Upvotes: 0

Ivan Yuriev
Ivan Yuriev

Reputation: 488

The main problem is that you can't await a method that is not async. You should rewrite your GetAllProduct method to make it async with the following signature:

public static async Task<IEnumerable<Product>> GetAllProduct()

Also don't forget to use Async methods to get your data from database:

    ...
    await con.OpenAsync();
    ...
    SqlDataReader rdr = await cmd.ExecuteReaderAsync();
    while (await rdr.ReadAsync())
    {
        ...
        students.Add(product);
    }
    return students;

Upvotes: 3

Related Questions