Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to track Linq2Db add,update,delete events?

Tags:

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?

like image 741
Dmitrij Polyanin Avatar asked Dec 25 '18 19:12

Dmitrij Polyanin


1 Answers

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.

like image 56
Svyatoslav Danyliv Avatar answered Sep 27 '22 20:09

Svyatoslav Danyliv