In this article, we will learn how to create SignalR database update notifications using SQL dependency in ASP.NET MVC 6. The following are the steps that we want to enable within the SQL Server first.
1. Enable Service Broker on the database
The following is the query that require to enable the service broker:
ALTER DATABASE BlogDemos SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE;

2. Now Add Connection string to the Web.Config file and the following code:
<add name=”DefaultConnection” connectionString=”Server=servername;Database=databasename;User Id=userid;Password=password;” providerName=”System.Data.SqlClient” />

3. Next step, Enable the SQL Dependency
In Global.asax start the SQL Dependency in App_Start() event and Stop SQL dependency in the Application_End() event and write the following code:
public class MvcApplication : System.Web.HttpApplication
{
string connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
GlobalConfiguration.Configure(WebApiConfig.Register);
//Start SqlDependency with application initialization
SqlDependency.Start(connString);
}

protected void Application_End()
{
//Stop SQL dependency
SqlDependency.Stop(connString);
}
}


4. Install SignalR from the Nuget
Run the following command in the Package Manager Console
Install-Package Microsoft.AspNet.SignalR

5. And then, Make a SignalR Hub Class
Make MessagesHub class in the Hubs folder
public class MessagesHub : Hub
{
private static string conString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
public void Hello()
{
Clients.All.hello();
}


[HubMethodName("sendMessages")]
public static void SendMessages()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MessagesHub>();
context.Clients.All.updateMessages();
}
}


6. Get the Data from the Repository
Make MessagesRepository to get the messages from the database when data is updated.
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();
}
}

7. Next step, you must Register SignalR at startup class
Write the following code:
app.MapSignalR();

8. View Page
Create div messagesTable that will append the table data from the database
<div class="row">
<div class="col-md-12">
   <div id="messagesTable"></div>
</div>
</div>


Now Add the SignalR related scripts in the page.
getAllMessages is a function that return the partialview data and bind it into the messagesTable div.
<script src="/Scripts/jquery.signalR-2.1.1.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/signalr/hubs"></script>

<script type="text/javascript">
$(function () {
    // Declare a proxy to reference the hub.
    var notifications = $.connection.messagesHub;
  
    //debugger;
    // Create a function that the hub can call to broadcast messages.
    notifications.client.updateMessages = function () {
        getAllMessages()
      
    };
    // Start the connection.
    $.connection.hub.start().done(function () {
        alert("connection started")
        getAllMessages();
    }).fail(function (e) {
        alert(e);
    });
});
function getAllMessages()
{
    var tbl = $('#messagesTable');
    $.ajax({
        url: '/home/GetMessages',
        contentType: 'application/html ; charset:utf-8',
        type: 'GET',
        dataType: 'html'
    }).success(function (result) {
        tbl.empty().append(result);
    }).error(function () {
       
    });
}
</script>


9. Create Partial View Page
Create a partial view _MessagesList.cshtml that returns all the messages.
@model IEnumerable<SignalRDbUpdates.Models.Messages>

<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
    <th>@Html.DisplayNameFor(model => model.MessageID)</th>
    <th>
        @Html.DisplayNameFor(model => model.Message)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.EmptyMessage)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.MessageDate)
    </th>
   
</tr>

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.MessageID)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Message)
    </td>
    <th>
        @Html.DisplayFor(modelItem => item.EmptyMessage)
    </th>
    <td>
        @Html.DisplayFor(modelItem => item.MessageDate)
    </td>
   
</tr>
}
</table>

10. Set Up the Database
Create the database called blogdemos and run the following script:
USE [BlogDemos]
GO

/****** Object:  Table [dbo].[Messages]    ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Messages](
[MessageID] [int] IDENTITY(1,1) NOT NULL,
[Message] [nvarchar](50) NULL,
[EmptyMessage] [nvarchar](50) NULL,
[Date] [datetime] NULL,
CONSTRAINT [PK_Messages] PRIMARY KEY CLUSTERED
(
[MessageID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Messages] ADD  CONSTRAINT [DF_Messages_Date]  DEFAULT (getdate()) FOR [Date]
GO


11. Let's Run the project
When eve data is inserted into the table the dependency_OnChange method will fire.