问题描述
我将SignalR与MVC一起使用,并在sqlDependency的Change Event上创建。但是当我在数据库中更新时它不会触发。当我在Db中执行查询“ ALTER DATABASE MyDatabase SET ENABLE_broKER”
我在NotificationComponent中写过
public void RegisterNotification(DateTime currentTime)
{
string conStr = ConfigurationManager.ConnectionStrings["sqlConString"].ConnectionString;
string sqlCommand = @"SELECT * from [dbo].[Event] where UpdatedTime > @UpdatedTime";
sqlDependency.Start(conStr);
using (sqlConnection con = new sqlConnection(conStr))
{
if (con.State != System.Data.ConnectionState.Open)
{
con.open();
}
sqlCommand cmd = new sqlCommand(sqlCommand,con);
cmd.Parameters.AddWithValue("@UpdatedTime",currentTime);
cmd.Notification = null;
sqlDependency sqlDep = new sqlDependency(cmd);
//sqlDep.OnChange += new OnChangeEventHandler(sqlDep_OnChange);
sqlDep.OnChange += sqlDep_OnChange;
//we must have to execute the command here
cmd.ExecuteReader().dispose();
//using (sqlDataReader reader = cmd.ExecuteReader())
//{
// // nothing need to add here Now
//}
}
}
public void sqlDep_OnChange(object sender,sqlNotificationEventArgs e)
{
if (e.Type == sqlNotificationType.Change)
{
sqlDependency sqlDep = sender as sqlDependency;
sqlDep.OnChange -= sqlDep_OnChange;
//from here we will send notification message to client
var notificationHub = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
notificationHub.Clients.All.notify("added");
//re-register notification
RegisterNotification(DateTime.Now);
}
}
public List<Event> GetEvents(DateTime afterDate)
{
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
return dc.Events.Where(a => a.UpdatedTime > afterDate).OrderByDescending(a => a.UpdatedTime).ToList();
}
}
在JS中
var notificationHub = $.connection.notificationHub;
$.connection.hub.start().done(function () {
console.log('Notification hub started');
});
notificationHub.client.notify = function (message) {
if (message && message.toLowerCase() == "added") {
updateNotificationCount();
}
}
在Startup.cs配置功能中:
app.MapSignalR();
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)