Operation is not valid due to the current state of the object. in C#
I had created this method to check number of this record in the table but it gives me this error message when the value of count(*) is 0 i use this library to connect oracle db
using Oracle.DataAccess.Client;
private int checkPort(int portID)
{
int intCount = 0;
try
{
OracleCommand oraCommand = new OracleCommand();
oraCommand.Connection = new DBManager().getConnection();
oraCommand.CommandText = "select count(*) as num from wireless_port_oid where port_id=:port_id";
oraCommand.Parameters.Add(":port_id", portID);
OracleDataReader Reader= oraCommand.ExecuteReader();
return intCount;
while (**Reader.Read()**)//it gives exception here
//The err Operation is not valid due to the current state of the object.
{
intCount =Convert.ToInt32(Reader[0]);
Reader.Close();
oraCommand.Connection.Close();
oraCommand = null;
if (intCount > 0)
{
return 1;
}
}
Reader.Close();
Reader.Dispose();
oraCommand.Connection.Close();
oraCommand.Connection.Dispose();
oraCommand.Dispose();
return 0;
}
catch (OracleException exception)
{
Console.WriteLine(exception.Message);
return 0;
}
}
You're closing the reader on Count = 0 and then trying to read it again in the while loop.
while (Reader.Read())//it gives exception here
//The err Operation is not valid due to the current state of the object.
{
intCount =Convert.ToInt32(Reader[0]);
Reader.Close();
oraCommand.Connection.Close();
oraCommand = null;
if (intCount > 0)
{
return 1;
}
// if intCOunt == 0 then what? loop again
}
But your code is not valid - I just noticed that you have a return intCount; just before the line you says has an error. I assume that that's just example typo.
I would refactor your code to take adavantage of C#'s using statement:
private int checkPort(int portID) {
string sql = "select count(*) as num from wireless_port_oid where port_id=:port_id";
int intCount = 0;
try {
using(OracleCommand oraCommand = new OracleCommand()) {
using(oraCommand.Connection = new DBManager().getConnection()) {
oraCommand.CommandText = sql;
oraCommand.Parameters.Add(":port_id", portID);
intCount = oraCommand.ExecuteScalar();
}
}
}
catch (OracleException exception) {
Console.WriteLine(exception.Message);
// may be you shouldn't return 0 here possibly throw;
}
return intCount;
}
链接地址: http://www.djcxy.com/p/61542.html
上一篇: 如何将@model指令更改为剃须刀视图中的不同模型?
下一篇: 由于对象的当前状态,操作无效。 在C#中