.Net Core Npgsql แถลงการณ์ที่เตรียมไว้

Sep 09 2020

ฉันพยายามเปลี่ยนคำสั่ง SQL บางคำสั่งในแอป. Net Core เพื่อให้สามารถใช้ซ้ำได้มากขึ้นโดยใช้คำสั่งที่เตรียมไว้ แต่ฉันมีปัญหากับ NpgsqlDbType

ฉันได้พยายามทำตามคำแนะนำของเอกสารแล้ว

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

แต่มันล้มเหลวในการรวบรวมกล่าวว่า

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

ฉันพลาดอะไรไปรึเปล่า? ฉันจะใช้ NpgsqlDbType ได้อย่างไร?

อัปเดต

ฉันแค่ใส่สิ่งที่ต้องทำขั้นสุดท้ายไว้ที่นี่เผื่อว่าจะเป็นประโยชน์ต่อคนอื่น

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

คำตอบ

2 ESG Sep 09 2020 at 02:16

NpgsqlDbType อยู่ในเนมสเปซ NpgsqlTypes ตรวจสอบให้แน่ใจว่าคุณมีการใช้ NpgsqlTypes ที่ด้านบน

หากคุณต้องการตั้งค่าพร้อมกันให้ใช้AddWithValueแทนAdd

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

หากคุณต้องการเพิ่มพารามิเตอร์เพียงครั้งเดียวและดำเนินการหลาย ๆ ครั้งคุณสามารถอ้างอิงถึงพารามิเตอร์ได้

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

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