使用Dapper.net执行MERGE

时间:2017-05-02 12:49:27

标签: dapper

我们正在使用Dapper.net作为ASP.net MVC 5应用程序中的数据层。

一个操作需要使用MERGE命令(如果TitleID存在,更新记录,如果没有,则插入它) - 类似这样:

MERGE BookInventory bi
USING BookOrder bo
ON bi.TitleID = bo.TitleID
WHEN MATCHED THEN
  UPDATE
  SET bi.Quantity = bi.Quantity + bo.Quantity
WHEN NOT MATCHED BY TARGET THEN
  INSERT (TitleID, Title, Quantity)
  VALUES (bo.TitleID, bo.Title,bo.Quantity);

可以使用Dapper将值映射到此MERGE语句吗?

我在这方面找不到任何内容,目前还不清楚在Dapper.net上使用MERGE的最佳方法是什么?

2 个答案:

答案 0 :(得分:4)

刚刚发现您可以像在.NET Fiddle代码中一样执行此操作:https://dotnetfiddle.net/e2G3Ho

在下面粘贴代码

// @nuget: Dapper -Version 1.60.6

using Dapper;
using System;
using System.Data.SqlClient;
using System.Linq;
using System.Collections.Generic;

public class Program
{    
    public class OrderDetail
    {
        public int OrderDetailID { get; set; }
        public int OrderID { get; set; }
        public int ProductID { get; set; }
        public int Quantity { get; set; }
    }

    public static void Main()
    {
        string sql = "SELECT * FROM OrderDetails";
        string sql2 = @"MERGE INTO OrderDetails AS TARGET 
            USING (
            VALUES
                (@OrderDetailID, @OrderID, @ProductID, @Quantity)
            ) AS SOURCE (OrderDetailID, OrderID, ProductID, Quantity)
            ON SOURCE.OrderDetailID = TARGET.OrderDetailID
            WHEN MATCHED THEN
            UPDATE SET Quantity = 666
            WHEN NOT MATCHED THEN
            INSERT (OrderID, ProductID, Quantity)
            VALUES (SOURCE.OrderID, SOURCE.ProductID, SOURCE.Quantity);
            "; 

        using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
        {   
            List<OrderDetail> details = new List<OrderDetail> {
                {new OrderDetail() {OrderDetailID = 1, OrderID = 1024, ProductID = 42, Quantity = 1000} },
                {new OrderDetail() {OrderDetailID = 9999, OrderID = 10268, ProductID = 42, Quantity = 1000} }
            };

            connection.Execute(sql2, details);
            var orderDetails = connection.Query<OrderDetail>(sql).ToList();

            FiddleHelper.WriteTable(orderDetails);
        }
    }
}

答案 1 :(得分:1)

未经测试,但这应该可以解决问题:

const string sql = @"
    merge into SomeTable as Target
    using (select @myId AS id) as Source
    on (Target.id = Source.id)
    when matched then
        update set Target.SomeColumn = @myValue
    when not matched by Target then
        insert (SomeColumn) values (@myValue)";

conn.Execute(sql, new { myId = 999, myValue = 123 })