I have a class Media
that is mostly 1-to-1 with my DB table Media
. I'm updating the table using Dapper.Contrib's Update
SqlConnection
extension method by passing in a Media
object.
One of my the columns of the table (and the corresponding class property) is OwnerID
, simply it is the ID of the user who first created this media. It should be written on the first insert (which is also done using Dapper.Contrib's Insert
extension method), and then updates shouldn't change it. Is it possible to accomplish this with just Dapper.Contrib? If possible I don't want to read the OwnerID
column before doing updates just to ensure the OwnerID
object property is the same.
The [Computed]
attribute seems to omit this column from both Update
and Insert
The description here seems to indicate this attribute should only omit writing to the column on updates which gives me hope that I am simply using the library incorrectly.
Unfortunatelly, Dapper.Contrib can't do what you want. The point is that according to sources extension method
Insert<T>
andUpdate<T>
has completely the same mechanism to collect the fields, that will be affected. Basically it looks like:So these methods always affects the same set of fields. To achieve your target behavior, you need to write your own extension and attribute. There are a lot of code below and I don't think, that it is elegant solution. However you are free to use and rework it as you need. It is a rough synchronous implementation, so consider it just as example, than can help you to develop your own solution. Here is a test example for custom
MyUpdate<T>
extension method:Table in DB:
Here is attribute to mark properties, that can't be used in Update queries:
And here is a little bit reworked extension method, that considers attribute
NotUpdatable
:Hope it helps.