I am having a error with dapper and async method. What am I doing wrong?
This is my code.
public Task<IEnumerable<Student>> GetStudentsAsync(int type)
{
var sql = "[dbo].[StudentController_GetStudents]";
var students = Connection.QueryAsync<Student>(sql,
new
{
type
},
commandType: CommandType.StoredProcedure
);
return students;
}
public Task<IEnumerable<Teacher>> GetTeachersAsync(int type)
{
var sql = "[dbo].[StudentController_GetTeachers]";
var teachers = Connection.QueryAsync<Teacher>(sql,
new
{
type
},
commandType: CommandType.StoredProcedure,
);
return teachers;
}
var studentsTask = StudentDao.GetStudentsAsync(type);
var teachersTask = StudentDao.GetTeachersAsync(type);
UpdateStudents(await studentsTask);
UpdateTeachers(await teachersTask);
I am having an error when I call "await teachersTask", the stack trace error is:
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Dapper.SqlMapper.<QueryAsync>d__23`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
Can anyone tell me what am I doing wrong? I want to execute both queries same time, and then wait for the result. I know is something with SQL connection is not open or something, but dont know how to fixed it.
Thanks in advance.
Use this private method to open a connection with SQL, and use GetStudents to get the students and same goes for teachers.
private SqlConnection GetConnection()
{
return new SqlConnection("ConnectionString");
}
public async Task<IEnumerable<Student>> GetStudentsAsync(int type)
{
using (var connection = GetConnection())
{
DynamicParameters param = new DynamicParameters();
param.Add("@type", type);
var result = await connection.QueryAsync<Student>("[dbo].[StudentController_GetStudents]",param, commandType: CommandType.StoredProcedure);
return result.ToList();
}
}
public async Task<IEnumerable<Teacher>> GetTeachersAsync(int type)
{
using (var connection = GetConnection())
{
DynamicParameters param = new DynamicParameters();
param.Add("@type", type);
var result = await connection.QueryAsync<Student>("[dbo].[StudentController_GetTeachers]",param, commandType: CommandType.StoredProcedure);
return result.ToList();
}
}
UpdateStudents(await StudentDao.GetStudentsAsync(type));
UpdateTeachers(await StudentDao.GetTeachersAsync(type));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.