简体   繁体   中英

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.

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

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();
}
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM