当我不使用sqldependency

时间:2019-02-14 11:14:22

标签: c# sql-server asp.net-mvc database sqldependency

我想以各种方式更新表数据或删除表数据时调用C#方法,例如sql newquery'从[dbo]删除top(1)。[叶子]',并使用存储过程调用c#方法。我在sql依赖项上执行它,但是我不需要这个,我使用存储过程执行它。您可以看到我的sqldependecey代码。但我想使用存储过程调用此方法的另一种方法。

public class NotificationEvent
{
    private delegate void RateChangeNotification(DataTable table);
    private SqlDependency dependency;
    string ConnectionString = @"Data Source=.;Initial Catalog=Message;Integrated Security=True";
    string UserName = Environment.UserName;

    public void RegisterForNotification()
    {
        var connectionString = ConnectionString;
        using (var connection = new SqlConnection(connectionString))
        {
            connection.Open();

            var queryString = "SELECT [ID] FROM [dbo].[Leaves]";
            using (var oCommand = new SqlCommand(queryString, connection))
            {
                // Starting the listener infrastructure...
                SqlDependency.Start(connectionString);

                var oDependency = new SqlDependency(oCommand);
                oDependency.OnChange += OnNotificationChange;

                // NOTE: You have to execute the command, or the notification will never fire.
                oCommand.ExecuteReader();
            }
        }
    }


    private void OnNotificationChange(object sender, SqlNotificationEventArgs e)
    {
        Console.WriteLine("Notification Info: " + e.Info);
        //Re-register the SqlDependency. 
        //var oDependency = new SqlDependency();
        //oDependency.OnChange += OnNotificationChange;
        RegisterForNotification();
    }
}

1 个答案:

答案 0 :(得分:0)

@Umar Asif如果您面临的问题完全是关于DB到DB的通信,那么我建议在SQL Server(使用Publisher-Subscriber)设计中在DB之间使用一个称为“合并复制”的概念:

https://docs.microsoft.com/en-us/sql/relational-databases/replication/merge/merge-replication?view=sql-server-2017

否则,如果您的问题仅需要通过调用C#方法来解决,请参阅:

How to call C# function in stored procedure