How can I track events on adding, updating or deleting entity rows with Linq2Db?
I need to recalculate some data in db on this operations, what is the best way?
On Entity Framework I use my custom Repository class with custom Add operations. Mabe this is only way in Linq2Db, but I am interesing, mabe there is some catcher to notify this events?
It is not so easy as in EF, because linq2db manipulates with SQL and you can easily update thousands records by single update statement. For example
db.SomeEntities.Where(e => e.IsExpired)
.Set(e => e.ExpirationDate, e => Sql.CurrentTimestamp)
.Update();
The same technique can be used with insert from
, update from
, delete
.
But there is possibility to catch SQL AST before executing. You have to override ProcessQuery
method in your DataConnection
class.
Sample is here: ConcurrencyCheckTests.cs
You should return the same statement that is passed to method but with changed property statement.IsParameterDependent = true
to prevent query caching.
SqlStatement
analysis is not trivial task but possible. You have to handle SqlUpdateStatement
, SqlInsertStatement
, SqlDeleteStatement
, SqlInsertOrUpdateStatement
.
Second option is to write your own extensions which manipulates with single objects, for example, UpdateTracked()
, DeleteTracked()
, etc. But as you can see from first example it will not help in complex queries.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With