We are using Dapper.net for the data layer in an ASP.net MVC 5 app.
One operation requires the use of the MERGE command (if the TitleID exists, update the record, if it doesn't, insert it) - something like this:
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);
Can Dapper be used to map values onto this MERGE statement?
I can't find anything on this and it's unclear what the best approach to using MERGE with Dapper.net is?
Untested, but this should do the trick:
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 })