在丢失范围之前处置对象(SqlCommand)

时间:2014-09-16 09:14:59

标签: c# sql ado.net

如何在返回之前处理“命令”而不影响返回类型?
“可靠性错误CA2000(CA2000: Dispose objects before losing scope)”

        SqlCommand command = new SqlCommand(sqlCmd);
        command.CommandTimeout = 240;
        if (applicationId == int.MinValue)
            command.Parameters.AddWithValue("@ApplicationId", DBNull.Value);
        else
            command.Parameters.AddWithValue("@ApplicationId", applicationId);


        return DB.ExecuteDataset(command);

1 个答案:

答案 0 :(得分:1)

以Jeopardy的风格:"什么是using声明?"

using(SqlCommand command = new SqlCommand(sqlCmd))
{
    command.CommandTimeout = 240;
    if (applicationId == int.MinValue)
        command.Parameters.AddWithValue("@ApplicationId", DBNull.Value);
    else
        command.Parameters.AddWithValue("@ApplicationId", applicationId);


    return DB.ExecuteDataset(command);
}