在CSDN论坛上看到下列问题,如果把DataReader当作DataGrid的DataSource,在DataGrid.DataBind()之后,在下列两种情形下,DataReader的IsClosed的值是不同的
1.
IDataReader reader = SomeDBCommand.ExecuteReader();
DataGrid1.DataSource = reader;
DataGrid1.DataBind();
在这里,reader的IsClosed的值是false
2.
IDataReader reader = SomeDBCommand.ExecuteReader(CommandBehavior.CloseConnection);
DataGrid1.DataSource = reader;
DataGrid1.DataBind();
在这里,reader的IsClosed的值是true
结论是,如果DataReader的CommandBehavior是CloseConnection的话,DataGrid1.DataBind()在某种(也许是非直接的)方式下,调用了DataReader的Close方法。在网上找到了一个类似的讨论,但他们没有给出原因。
把DataReader作为DataGrid的DataSource时,DataReader是当作IEnumerable来看待的,从IEnumerable可以获取IEnumerator,然后可以用它的MoveNext/Current来依次获取每个记录,难道MoveNext调用了DataReader的Close方法?做了个试验
using System;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Collections;
class TestClose
{
static void Main()
{
SqlConnection conn = new SqlConnection("server=localhost;database=pubs;uid=sa;pwd=;");
SqlCommand cmd = new SqlCommand("select * from authors", conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
TestRead(reader);
reader.Close();
conn.Open();
reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
TestMoveNext(reader);
reader.Close();
}
static void TestRead(IDataReader reader)
{
while (reader.Read());
Console.WriteLine("after Read(), reader is closed? {0}", reader.IsClosed);
}
static void TestMoveNext(IDataReader reader)
{
IEnumerator e = ((IEnumerable)reader).GetEnumerator();
while (e.MoveNext());
Console.WriteLine("after MoveNext(), reader is closed?{0}", reader.IsClosed);
}
}
输出是
after Read(), reader is closed? False
after MoveNext(), reader is closed? True
果不其然啊,用Lutz Roeder的Reflector(大力推荐!)工具看了一下.NET里SqlDataReader的实现
IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new DbEnumerator(this, (CommandBehavior.Default != (CommandBehavior.CloseConnection & this._behavior)));
}
可见SqlDataReader的CommandBehavior确实是传进去的,再看DbEnumerator的实现
public DbEnumerator(IDataReader reader, bool closeReader)
{
if (reader == null)
{
throw ADP.ArgumentNull("reader");
}
this._reader = reader;
this.closeReader = closeReader;
}
public bool MoveNext()
{
object[] objArray1;
if (this._schemaInfo == null)
{
this.BuildSchemaInfo();
}
this._current = null;
if (this._reader.Read())
{
objArray1 = new object[this._schemaInfo.Length];
this._reader.GetValues(objArray1);
this._current = new DbDataRecord(this._schemaInfo, objArray1, this._descriptors, this._fieldNameLookup);
return true;
}
if (this.closeReader)
{
this._reader.Close();
}
return false;
}
果然, 如果DataReader的CommandBehavior是CommandBehavior.CloseConnection的话,MoveNext调用了Close方法!