Is it possible to perform an insert or update with the following constraints :
- Dapper is used in the project
- The Primary Key is auto-incrementing positive
- The newly inserted data may not have a PK value (or has a value of
0
) - The data needs to have the PK value on a newly inserted row.
- The query is being generated procedurally, and generalizing it would be preferable
Something like :
int newId = db.QueryValue<int>( <<insert or update>>, someData );
I have read about different solutions, and the best solution seems to be this one :
merge tablename as target
using (values ('new value', 'different value'))
as source (field1, field2)
on target.idfield = 7
when matched then
update
set field1 = source.field1,
field2 = source.field2,
...
when not matched then
insert ( idfield, field1, field2, ... )
values ( 7, source.field1, source.field2, ... )
but
- it seems to fail on the third constraint and
- it does not guarantee to return the newly generated id.
Because of the 5th constraint (or preferance), a stored procedure seems overly complicated.
What are the possible solutions? Thanks!