问题
Let me start by posting my code first:
ExecuteScalar method:
public T ExecuteScalar<T>(string sql, CommandType commandType, List<NpgsqlParameter> parameters)
{
using (NpgsqlConnection conn = Konekcija_na_server.Spajanje("spoji"))
{
return Execute<T>(sql, commandType, c =>
{
var returnValue = c.ExecuteScalar();
return (returnValue != null && returnValue != DBNull.Value && returnValue is T)
? (T)returnValue
: default(T);
}, parameters);
}
}
Execute method:
T Execute<T>(string sql, CommandType commandType, Func<NpgsqlCommand, T> function, List<NpgsqlParameter> parameters)
{
using (NpgsqlConnection conn = Konekcija_na_server.Spajanje("spoji"))
{
using (var cmd = new NpgsqlCommand(sql, conn))
{
cmd.CommandType = commandType;
if (parameters.Count > 0 )
{
foreach (var parameter in parameters)
{
cmd.Parameters.AddWithValue(parameter.ParameterName,parameter.Value);
}
}
return function(cmd);
}
}
}
Call of ExecuteScalar method:
komanda = "begin;select count(*) from radni_sati where ime=@ime and prezime=@prezime" +
" and (dolazak is not null and odlazak is not null and sati_rada is not null) and napomena='' ;commit;";
listaParametara.Add(new NpgsqlParameter { ParameterName = "@ime", Value = ime });
listaParametara.Add(new NpgsqlParameter { ParameterName = "@prezime", Value = prezime });
var nePrazni_redovi=instanca.ExecuteScalar<int>(komanda, CommandType.Text, listaParametara);
listaParametara.Clear();
Now my problem is when I call ExecuteScalar()
.
For some reason my ExecuteScalar
always returns 0 as result and that can't be coz I tested it as a normal query in PSQL Shell and it always returns values>0 when I call legit query that has to return normal value.
First time It enters ExecuteScalar
after a call, returns a returnValue
from lamba operator and for example its 16, then when it goes to Execute function, somehow it returns 0 and I dont understand why, coz main thing I need ExecuteScalar
for is to return count(*)
value out as an int
.
回答1:
can you tell us how are you calling ExecuteScalar? What type is T? Also, set breakpoint to: var returnValue = c.ExecuteScalar();
and check what type is returned after you step over that line (F10). In watch window of Visual Studio you should check Type column.
来源:https://stackoverflow.com/questions/46629568/executescalar-not-returning-right-values-c-sharp