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).
[…] of what needs to happen in this part is documented in this post. In your ASP.NET MVC project, choose a random controller action and paste following […]
This is really nice article. I’ve tried the code on my local machine by just change connection and query.
But I don’t understand why “There was a change” message is keep on coming even though there isn’t any change made me.
Shouldn’t it only be fired in case when changes occur in the database?
I ‘ve tested your work and it’s wonderful but when I retrive data appear error :
The calling thread cannot access this object because a different thread owns it
What does it mean?
bye
Thanks mate, this is still usefull!!!