I am trying to get int value from the database but It is throwing an error
Unable to cast object of type 'System.Byte' to type 'System.Int32'.
In the database, Active field is tinyint.
Also, how to return both values from this method.
private string CheckData(string firstValue, string SecondValue, int Active)
{
string Data = "";
StringBuilder sb = new StringBuilder();
string query = @"select M.ident Mi, mmp.active Active
from Iden.Iden M
inner join PtM.MPt MMP on MMP.mPat = M.id
where M.ident = 'firstValue'
and Mi.ident = 'SecondValue'";
sb.Append(query);
sb.Replace("firstValue", firstValue);
sb.Replace("SecondValue", SecondValue);
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sb.ToString());
cmd.CommandTimeout = 0;
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
try
{
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Data = reader.GetString(reader.GetOrdinal("Mi"));
Active = reader.GetInt32(reader.GetOrdinal("Active"));
}
}
}
catch (Exception ex)
{
_log.Error($"Exception:{ex.Message}");
}
finally
{
connection.Close();
connection.Dispose();
}
return Data;
}
TINY_INTnot anINT. A tiny int maps to abytein .NET code. The reader reads it as an object, which means that the actually representation will be as a boxed byte. You can only unbox boxed values to their actual type. If you want to represent it as an integer in your code, you will need to unbox it to abytefirst and then cast the byte to anint:Active = (int) reader.GetByte(reader.GetOrdinal("Active"));StringBuilder.Replace, and 2) since you are fishing out the ordinal values, do it once (before going into thewhileloop) rather than doing on each pass through the loop. Your code may end up noticeably faster (if you have enough rows):var dataOrdinal = reader.GetOrdinal("Mi");and similar foractiveOrdinal. Then using them in the GetXxx methods.Activecolumn declared in your SQL Schema. Is it aBit? If so, consider makingActiveaboolin your C# code and usingreader.GetBool(). Oh, and you should dispose your data reader. Read up on using theusingkeyword for disposing IDisposable objectsDataandActive. Also, how to get thebooleanif I do not want to useint.tinyintin the SQL schema. Could you please provide me proper solution for this. Thanks