核心2.1 SignalR和SQLDependency

时间:2018-08-01 15:36:05

标签: signalr sqldependency asp.net-core-2.1

是否有任何 Core 2.1 示例可用于将SignalR与SQLDependency结合使用。 确实启用了代理等功能,但是从不依赖于onChange事件触发。仅事件订阅被触发。 当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");
        }
    }
}

}

1 个答案:

答案 0 :(得分:0)

问题在一行之内:

var cmd =新的SqlCommand(@“ SELECT ID,Name_en,CountryId,来自[dbo] .Cities的代码”,conn)

必须使用字段名称(而不是*)以及2部分表名称约定=> [dbo]。城市