I'm trying to implement a repository with Dapper as ORM, I want inserted or updated entities to be returned back. This is what I came up with, it works just fine but I'm wondering if this is abusing the default Query and QueryAsync methods?
public async Task<Models.TestTable> Insert(Models.TestTable inputObject)
{
IEnumerable<Models.TestTable> output;
output = await _connection.QueryAsync<Models.TestTable>(
sql: string.Format("INSERT INTO TestTable (FirstName, LastName) OUTPUT INSERTED.* VALUES (@FirstName, @LastName)"),
param: inputObject);
return output.SingleOrDefault();
}
The only actual problem I can see there is the unnecessary string.Format
.
Personally I might have been tempted to just update the Id
(or whatever) in the existing object, but your OUTPUT INSERTED.*
works fine too. I might be very tempted to move the local declaration inline via var output = ...
, and of course once I've done that it makes it tempting to make the entire thing inline:
public async Task<Models.TestTable> Insert(Models.TestTable inputObject)
=> (await _connection.QueryAsync<Models.TestTable>(
"INSERT INTO TestTable (FirstName, LastName) OUTPUT INSERTED.* VALUES (@FirstName, @LastName)",
inputObject)).SingleOrDefault();
but most of that is trivia and subjective. Heck, even the string.Format
is just unnecessary rather than problematic.
One other thing to check: did we (and I can't remember!) add a QuerySingleOrDefaultAsync
method? I know we added QuerySingleOrDefault
- I just can't remember about the *Async
twin.