Core 2.1 SignalR and SQLDependency



是否有Core 2.1示例可用于将SignalR与SQLDependency一起使用。确实启用了broker等,但从未获得对Change事件触发的任何依赖。仅触发事件订阅。当MS-SQL数据库表Cities在后端发生更改时,我希望看到更改立即反映在客户端网页上,而无需刷新/重新加载页面。

//在ConfigureServices中启动应用程序时启动依赖项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].Colies",conn(

需要使用字段名称(不是*(以及由两部分组成的表名称约定=>[dbo]。城市

相关内容

  • 没有找到相关文章

最新更新