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;
}
}
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;