我正在尝试从调用存储过程的数据访问类返回 XMLReader 以运行 FOR XML 查询。问题是,当我返回 xmlreader 时,我无法在 sql 连接上调用 close(),否则读取将终止。调用 xmlreader 的类对 sql 连接一无所知,因此它不能负责关闭连接。我该如何处理?
问问题
340 次
2 回答
3
您可以构建一个XmlDocument
并返回它,这样您就可以关闭该数据库连接。
于 2010-01-11T17:21:03.587 回答
1
使用匿名方法来包装调用。
例如,假设你有一个数据层类,在数据层添加一个类似的方法:
public delegate void DoSomethingInvoker();
class DataLayer
{
//myReader needs to be declared externally in other to access it from the doSomething delegate
public void MethodThatGetsAsXmlReader(XmlReader myReader, DoSomethingInvoker doSomething)
{
myReader = GetXmlReaderFromDB();
doSomething();
CloseDbConnection(); //close connections, do cleanup, and any other book keeping can be done after the doSomething() call
}
}
要调用/使用它,您只需在高级课程中执行此操作
DataLayer dl = new DataLayer();
XmlReader myReader = null; //variables declared outside the scope of the anonymous method are still accessible inside it through the magic of closures
dl.MethodThatGetsAsXmlReader(myReader, delegate()
{
//do all work that involves myReader here
myReader.read();
Console.out.println(myReader.value);
});
//at this point myReader is closed and cannot be used
基本上,您将要执行的代码传递给数据层,数据层获取 xmlreader,针对它调用您的代码,然后进行清理。
我使用类似的技术在我的代码中包装事务逻辑
DataLayer dl = new DataLayer();
dl.Transaction(delegate()
{
dl.DbCall1();
dl.DbCall2();
dl.DbCall3();
});
它使代码美观且可读,同时仍保持其组织性和分层性;
于 2010-01-11T18:11:57.787 回答