C# trigger after database changes with SQLDependency
I found the following amazing article with some code that works without any modifications. With SQLDependency, you can listen to database changes with a predefined query. If something happens to this result set (INSERT/DELETE/UPDATE) an event will be triggered, allowing you to take action. Assume following console application:
Two things need to be configured here: the connection string and the query you want to listen to. Please note that wildcard won’t work so you need to define your exact columns. Next up, the definition of the database listener:
SQLDependency starts listening as soon as you create a new instance of the listener class. it will actually start listening to your query if the start method is fired. If something happens on the database level that affects the defined query, the NotifyOnChange delegate will be called as well, allowing you to take action where necessary. An alternative approach of SQLDependency could be Quartz.NET, what would result in more of database polling system rather than event-based communication (at least from a developers perspective).