Yessir
Yessir

Reputation: 183

How to listen to database for changes?

Is it somehow possible in my C# Applications to listen for changes in the database?

For example, if there is a new insert in a table on my Database, I want my C# application to refresh and update the content.

Upvotes: 0

Views: 5101

Answers (4)

Mehdi
Mehdi

Reputation: 598

using System.Data.SqlClient;
using ServiceBrokerListener.Domain;

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;

    public Worker(ILogger<Worker> logger)
    {
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        try
        {
            const string cs = "CONNECTIONSTRING";
            SqlDependency.Start(cs);

            var listener = new SqlDependencyEx(cs, "DATABASE", "TABLE");
            listener.TableChanged += (o, e) => SqlDependencyTableChanged();
            listener.Start();
        }
        catch (TaskCanceledException ex)
        {
            var message = ex.Message;
        }
        catch (Exception ex)
        {
            var message = ex.Message;
        }
    }

    private void SqlDependencyTableChanged()
    {
        //DO_SOMETHING
    }
}

https://github.com/dyatchenko/ServiceBrokerListener

EDIT (.NET Core for linux):

IHost host = Host.CreateDefaultBuilder(args)
    .UseSystemd()
    .ConfigureServices(services =>
    {
        services.AddHostedService<Worker>();
    })
    .Build();

host.Run();

Upvotes: 1

Stefan
Stefan

Reputation: 17648

Is it somehow possible in my C# Applications to listen for changes in the database?

Yes and no.

Data updates from outside EF are not captured - you can use the SQL notifications as others suggest.

But for updates using EF itself, you can override SaveChanges of your DbContext and add event logic there.

public virtual int SaveChanges ();

See MSDN

Example:

//note: only works for saves triggered by the EF Core DbContext
public override int SaveChanges()
{
     //do you logic and invoke event
 
     //don't forget to call base
     return base.SaveChanges();
}

Upvotes: 0

ali azizan
ali azizan

Reputation: 311

You can use query notification in sql server by fllow the link https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/query-notifications-in-sql-server

Upvotes: 0

Ehssan
Ehssan

Reputation: 759

No, that is not possible using Entity Framework Core. If all changes to the database happen inside your application process, you could handle the change detection inside your application

If that's not possible and you need to listen for database changes you can use query notifications provided by Microsoft SQL Server

Upvotes: 5

Related Questions