Declaración preparada de .Net Core Npgsql

Sep 09 2020

He intentado cambiar algunas declaraciones SQL en una aplicación .Net Core para que sean más reutilizables mediante el uso de Declaraciones preparadas, pero tengo problemas con NpgsqlDbType.

Intenté seguir las instrucciones de documentación.

NpgsqlCommand command = new NpgsqlCommand (
    " select * from computers where com_phys = @com_phys ",
    dbconnection
);
command.Parameters.Add("com_phys", NpgsqlDbType.Varchar);
command.Prepare();

Pero está fallando en compilar, diciendo

The name 'NpgsqlDbType' does not exist in the current context

¿Me estoy perdiendo de algo? ¿Cómo utilizo NpgsqlDbType?

ACTUALIZAR

Solo estoy poniendo la última cosa funcional aquí en caso de que pueda beneficiar a alguien más.

// prepare

NpgsqlCommand command = new NpgsqlCommand (
    " select * from computers where com_phys = @com_phys ",
    dbconnection
);
var param01 = command.Parameters.Add("com_phys", NpgsqlDbType.Varchar);
command.Prepare();

// execute 01

param01.Value = "value01";
var results = command.ExecuteReader();
while(results.Read()) {
   // nothing
}
command.Close();

// execute 02

param01.Value = "value02";
var results = command.ExecuteReader();
while(results.Read()) {
   // nothing
}
command.Close();

Respuestas

2 ESG Sep 09 2020 at 02:16

NpgsqlDbType está en el espacio de nombres NpgsqlTypes. Asegúrese de tener un using NpgsqlTypes en la parte superior.

Si desea establecer el valor al mismo tiempo, utilice en AddWithValuelugar deAdd

NpgsqlCommand command = new NpgsqlCommand (
    " select * from computers where com_phys = @com_phys ",
    dbconnection
);
command.Parameters.AddValue("com_phys", NpgsqlDbType.Varchar, value);
// OR command.Parameters.AddValue("com_phys", NpgsqlDbType.Varchar, size, value);
// OR command.Parameters.AddValue("com_phys", value);
command.Prepare();

Si desea agregar el parámetro una vez y ejecutarlo varias veces, puede mantener una referencia al parámetro

var parameter = command.Parameters.Add("com_phys", NpgsqlDbType.Varchar);

// Later, in a loop
parameter.Value = "someValue";