signalr - 核心 2.1 SignalR 和 SQLDependency
问题描述
是否有任何Core 2.1示例可用于将 SignalR 与 SQLDependency 一起使用。是否启用了代理等,但从未获得任何对 onChange 事件触发的依赖。只是事件订阅被触发。当后端的 MS-SQL 数据库表 Cities 发生更改时,我希望看到更改立即反映在客户端网页上,而无需刷新/重新加载页面。
//在ConfigureServices中启动app时启动依赖 SqlDependency.Start(Configuration.GetConnectionString("DefaultConnection"));
using Microsoft.AspNetCore.SignalR;
using SignalR_Test4.Data;
using SignalR_Test4.Hubs;
using System.Collections.Generic;
using System.Data.SqlClient;
namespace SignalR_Test4.Models
{
public class CityRepository
{
private readonly ApplicationDbContext _context;
private readonly IHubContext<CityHub> _hubcontext;
public CityRepository(ApplicationDbContext context, IHubContext<CityHub> hubcontext)
{
_context = context;
_hubcontext = hubcontext;
}
public IEnumerable<City> GetCities()
{
List<City> listOf = new List<City>();
//listOf = _context.Cities;
using (var conn = new SqlConnection(GlobalVar.connectionString))
{
conn.Open();
using (var cmd = new SqlCommand(@"SELECT * FROM Cities", conn))
{
cmd.Notification = null;
SqlDependency dependency = new SqlDependency(cmd);
dependency.OnChange += Dependency_OnChange;
if (conn.State == System.Data.ConnectionState.Closed)
conn.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
listOf.Add(new City { Id = (string)reader["Id"], Name_en = (string)reader["name_en"], CountryId = (string)reader["CountryId"], Code = (string)reader["Code"] });
}
}
}
return listOf;
}
private void Dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
_hubcontext.Clients.All.SendAsync("GetCities");
}
}
}
}
解决方案
问题在于:
var cmd = new SqlCommand(@"SELECT Id, Name_en, CountryId, Code from [dbo].Cities", conn)
需要使用字段名称(不是 *)以及 2 部分表名称约定 => [dbo].Cities
推荐阅读
- c++ - 如何使用 LLVM IR API
- php - 有没有办法在查询中创建多个“WHERE”子句?
- java - 如何修复以下代码,以便获得输出的反向链表?
- reactjs - 将静态 React JS 应用程序部署到 Google Cloud Platform (GCP)?
- c# - EF Core 有两个 DbContext。如何指定表格?
- ios - 如何更改 textColor 或 MDCTextInputControllerOutlined
- r - 从 R 中 3 层数据框中的时间列中的日期中删除时间
- qaf - 如何从存储的变量访问 qaf 步骤中的对象字段
- elixir - 在 Phoenix Liveview 中,如何更改按钮标签以指示作业状态
- python - 使用 python 脚本从在线数据库下载数据