Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Database Change Listener C#

Tags:

I want to listen for changes to data in a SQL Server database from C#. I was hoping that there would be some sort of listener which I could use to determine if data that I have is stale. Despite being a fairly common scenario I can't find any solutions which aren't to simply poll the database.

I use Linq-To-SQL to access the data and hence have a DataContext object, I was hoping I could listen for an on data changed event but I can't seem to find one.

I appreciate that it's a non-trivial barrier (From C# method to SQL Server DB), the reason I expected this to be a solved problem is that it's a common requirement for GUIs. If it's not possible to Listen for updates how to you keep the Data displayed in a GUI fresh (When it's backed by a SQL Server data source).

Although this isn't for GUI work I was expecting to adapt something from that realm.

Is there a way to subscribe to SQL Server database change events in C#?

like image 852
gav Avatar asked Jul 29 '10 15:07

gav


People also ask

What is SqlDependency C#?

SqlDependency allows you to receive notifications when the original data in the database changes so that the cache can be refreshed. To set up a dependency, you need to associate a SqlDependency object to one or more SqlCommand objects. To receive notifications, you need to subscribe to the OnChange event.


2 Answers

I've never used them before, but have you tried SQL Server Events notifications? See this article: Getting Started with SQL Server Event Notifications

like image 57
João Pereira Avatar answered Oct 10 '22 23:10

João Pereira


You're looking for the SqlDependency class, which allows you to listen for changes to the resultset of a SQL query.

like image 26
SLaks Avatar answered Oct 11 '22 01:10

SLaks