如何使用Asp.Net MVC应用程序中的SqlDependency仅获取DB中已更改的记录

时间:2019-09-21 12:28:45

标签: signalr sqldependency

当数据库(SQL Server)中的记录发生更改时,我正在应用程序(ASP.NET MVC)中使用SQL依赖项来获取通知。我关注这篇文章SignalR Database Update Notifications in ASP.NET MVC using SQL Dependency,但是这篇文章并未显示如何仅检索数据库中已更改的记录(实体)。我必须进行更改的部分如下:

public class MessagesRepository
{
        readonly string _connString = 
        ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

        public IEnumerable<Messages> GetAllMessages()
        {
            var messages = new List<Messages>();
            using (var connection = new SqlConnection(_connString))
            {
                connection.Open();
                using (var command = new SqlCommand(@"SELECT [MessageID], 
                [Message], [EmptyMessage], [Date] FROM [dbo].[Messages]", connection))
                {
                    command.Notification = null;

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

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

                    var reader = command.ExecuteReader();

                    while (reader.Read())
                    {
                        messages.Add(item: new Messages 
                        { MessageID = (int)reader["MessageID"], 
                        Message = (string)reader["Message"], 
                        EmptyMessage =  reader["EmptyMessage"] != DBNull.Value ? 
                        (string) reader["EmptyMessage"] : "", 
                        MessageDate = Convert.ToDateTime(reader["Date"]) });
                    }
                }              
            }
            return messages;            
        }

        private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            if (e.Type == SqlNotificationType.Change)
            {
                MessagesHub.SendMessages();
            }
        }
    }

我将不胜感激。谢谢

0 个答案:

没有答案