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

编程入门 行业动态 更新时间:2024-10-28 02:32:41
本文介绍了为什么我成功读取的 Npgsql 数据消失了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下代码形状.似乎我误解了 C# 方法的返回值.一个完整"的枚举器怎么可能作为一个空的枚举器返回?

I have the following code shape. It seems that I'm misunderstanding the C# method return values. How is it possible that a "full" enumerator gets returned as an empty one?

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! } }

推荐答案

你没有详细说明你的连接来自哪里.假设它是这样的:

You don't detail where your connection is coming from. Assuming it's something like:

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(); } }

那么在你使用reader的地方,你必须要处置它来依次处置连接的底层连接到数据库:

Then where you use the reader, you have to dispose it to in turn dispose the connection's underlying connection to the database:

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

更多推荐

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

本文发布于:2023-10-23 23:15:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1522290.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:消失了   数据   Npgsql

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!