gpt4 book ai didi

c# - 为什么我读取成功的Npgsql数据消失了?

转载 作者:行者123 更新时间:2023-11-30 22:34:16 27 4
gpt4 key购买 nike

我有以下代码形状。看来我误解了 C# 方法的返回值。 “完整”枚举数怎么可能返回为空枚举数?

class ThingDoer
{
public NpgsqlDataReader DoQuery()
{
NpgsqlCommand c = new NpgsqlCommand(...);
NpgsqlDataReader dataread = c.ExecuteReader();
return dataread; // Debugger confirms that six data are enumerable here.
}
}

...

class OtherThing
{
public void higherLevelFunction()
{
NpgsqlDataReader result = myThingDoer.DoQuery();
result.Read(); // No data! result's enumerable returns nothing!
}
}

最佳答案

您没有详细说明您的连接来自何处。假设它是这样的:

public NpgsqlDataReader DoQuery()
{
using(NpgsqlConnection = GetConnectionCode())
{
NpgsqlCommand c = new NpgsqlCommand(...);
NpgsqlDataReader dataread = c.ExecuteReader();
return dataread;
}//Connection closes at this using-scope being left because that triggers Dispose()
}

然后将其更改为:

public NpgsqlDataReader DoQuery()
{
bool ownershipPassed = false;
NpgsqlConnection conn = GetConnectionCode();
try
{
NpgsqlCommand c = new NpgsqlCommand(...);
NpgsqlDataReader dataread = c.ExecuteReader(CommandBehavior.CloseConnection);
ownershipPassed = true;
return dataread;
}
finally
{
if(!ownershipPassed)//only if we didn't create the reader than takes charge of the connection
conn.Dispose();
}
}

然后在使用读取器的地方,必须处置它以依次处置连接的底层连接到数据库:

public void higherLevelFunction()
{
using(NpgsqlDataReader result = myThingDoer.DoQuery())
result.Read();
}

关于c# - 为什么我读取成功的Npgsql数据消失了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7903326/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com