如何在使用C#中的Dapper插入mysql数据库之前检查带有复合键的记录是否已存在

时间:2018-10-01 22:06:51

标签: c# mysql dapper

供应商和发票是包含9个字段的表格中的组合键

1 个答案:

答案 0 :(得分:0)

您可以简单地先执行SELECT查询,然后插入,也可以单次执行,如下所示(SQL Server)。您可以使用here

中列出的推荐的Dapper扩展程序之一
string cmd = @"IF NOT EXISTS (SELECT * FROM Table1 WHERE SupplierId=@SupplierId AND InvoiceId=@InvoiceId)
                    BEGIN 
                        INSERT INTO Table1(SupplierId, InvoiceId) VALUES(@SupplierId, @InvoiceId)
                    END";

using (var dbConn = new SqlConnection("Server=(local);Database=MyDatabase;Integrated Security=true"))
{
    dbConn.Execute(cmd, new { SupplierId = 1, InvoiceId = 2 });
}
Console.ReadKey();

更新 对于MySQL,您可以编写类似

INSERT INTO Table1 (SupplierId, InvoiceId) VALUES(@SupplierId, @InvoiceId) ON DUPLICATE KEY SupplierId=SupplierId

https://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html