我在带有SQL Server数据库的ASP.Net Core 2.1 CRUD应用程序中使用Dapper ORM。对于我正在开发的新表格,我想在调用屏幕时一次性检索所有参考数据(以填充SELECT
字段选项)。这涉及到一系列存储过程调用,我想异步执行这些过程以获得最佳性能。
This Dapper tutorial建议我考虑使用QueryMultipleAsync
,但找不到用于存储过程的示例,只能找到硬编码的SQL语句。
我的C#代码当前如下所示:
public async Task<ContactReferenceData> Get()
{
ContactReferenceData refData = new ContactReferenceData();
try
{
using (IDbConnection dbConnection = _connection)
{
dbConnection.Open();
var countryData = await dbConnection.QueryAsync<Country>(sql: "usp_GetCountries", commandType: CommandType.StoredProcedure);
refData.CountryDetails = countryData.AsList();
var companyData = await dbConnection.QueryAsync<Company>(sql: "usp_GetCompanies", commandType: CommandType.StoredProcedure);
refData.CompanyDetails = companyData.AsList();
var groupData = await dbConnection.QueryAsync<Group>(sql: "usp_GetGroups", commandType: CommandType.StoredProcedure);
refData.GroupDetails = groupData.AsList();
var groupPositionData = await dbConnection.QueryAsync<GroupPosition>(sql: "usp_GetGroupPositions", commandType: CommandType.StoredProcedure);
refData.GroupPositionDetails = groupPositionData.AsList();
}
return refData;
}
catch (Exception ex)
{
_logger.LogError(ex.ToString());
throw;
}
}
这在我的测试环境中可以正常工作,但是我不确定这是执行异步查询的正确方法。特别是,我有以下担忧:
它是否足够健壮,可以在实时操作中被信任?
以目前的形式,它是在最大限度地提高异步操作的优势(如果有),还是应该使用QueryMultipleAsync
来正确实现这一目标?
答案 0 :(得分:0)
您尝试过这样的事情吗?
public async Task<ContactReferenceData> Get()
{
var sql = "EXEC usp_GetCountries; EXEC usp_GetCompanies; EXEC usp_GetGroups; EXEC usp_GetGroupPositions";
ContactReferenceData refData = new ContactReferenceData();
try
{
using (IDbConnection dbConnection = _connection)
{
using (var multi = connection.QueryMultipleAsync(sql: sql, commandType: CommandType.StoredProcedure ).Result)
{
refData.CountryDetails = multi.Read<countryDetails>().ToList();
refData.CompanyDetails = multi.Read<CompanyDetails>().ToList();
refData.GroupData = multi.Read<Groups>().ToList();
refData.GroupPositionsData= multi.Read<GroupPositions>().ToList();
}
}
return refData;
}
catch (Exception ex)
{
_logger.LogError(ex.ToString());
throw;
}
}