如何使用SignalR在数据库更新时通知客户端?

时间:2017-06-30 05:37:43

标签: c# sql model-view-controller signalr sqldependency

namespace somename
{
    public class ClaimInfoRepository
    {
        public IEnumerable<ClaimInfo> GetData()
        {

            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
            {
                connection.Open();
                using (SqlCommand command = new SqlCommand(@"SELECT count(1) FROM [dbo].[table] WHERE ClaimStatus=8", connection))
                {
                    // Make sure the command object does not already have
                    // a notification object associated with it.
                    command.Notification = null;

                        SqlDependency dependency = new SqlDependency(command);
                        dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

                    if (connection.State == ConnectionState.Closed)
                        connection.Open();

                    using (var reader = command.ExecuteReader())
                        return reader.Cast<IDataRecord>()
                            .Select(x => new ClaimInfo()
                            {
                                ClaimStatus = x.GetInt32(0)
                            }).ToList();
                }
            }
        }
          void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            if (e.Type == SqlNotificationType.Change)
            {
                //from here we will send notification message to client
                IHubContext context = GlobalHost.ConnectionManager.GetHubContext<ClaimHub>();
                context.Clients.All.notify();
            }

        }
    }
}

如果我删除if条件if(e.Type == SqlNotificationType.Change)它有效,但它进入无限循环(一次又一次地通知),我想只通知一次是否有变化.. !!任何帮助都会得到赞赏..

0 个答案:

没有答案