[英]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. 我刚接触带有Web API 2的ASP.NET MVC,并且通过将带有Web API 2的asp.net MVC与ASP.NET MVC一起创建了异步和等待方法,该方法将存储到SQL DB中。 When I try to call my repository method in the API Controller I got an error cannot await ”system.collections.generic.list”. 当我尝试在API Controller中调用存储库方法时,出现错误,无法等待“ 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: 您应该重写GetAllProduct方法以使其与以下签名异步:
public static async Task<IEnumerable<Product>> GetAllProduct()
Also don't forget to use Async methods to get your data from database: 另外,不要忘记使用Async方法从数据库获取数据:
...
await con.OpenAsync();
...
SqlDataReader rdr = await cmd.ExecuteReaderAsync();
while (await rdr.ReadAsync())
{
...
students.Add(product);
}
return students;
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: 如果要跳过ADO.NET
样板文件,可以改用Dapper
( https://github.com/StackExchange/dapper-dot-net )简化代码:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.