开门见山,使用MS Enterprise Library的DAAB(Data Access Application Block)获取 数据时抛出异常。具体场景如下,通过Database对象的ExecuteReader执行两段Select语句, 前一句是不合法的,后一句是正确的。为了避免第一次执行出错导致程序的终止,特意将其 放到Try/Catch酷快中。两次数据库操作通过TrsanctionScope的形式纳入同一个Transaction 中,具体的代码如下所示。
class Program
{
static void Main()
{
string invalidSql = "SELECT * FROM {InvalidTable}";
string validSql = "SELECT * FROM {ValidTable}";
Database db = DatabaseFactory.CreateDatabase();
using (TransactionScope scope = new TransactionScope())
{
DbCommand commandWithInvalidSql = db.GetSqlStringCommand (invalidSql);
DbCommand commandWithValidSql = db.GetSqlStringCommand (validSql);
try
{
db.ExecuteReader(commandWithInvalidSql);
}
catch
{ }
db.ExecuteReader(commandWithValidSql);
}
}
}
但是在执行第二个ExecuteReader方法的时候却抛出如下一个InvalidOperationException (如下图),错误消息为:“ExecuteReader requires an open and available Connection. The connection's current state is closed.”