我正在尝试使用 LINQ 获取 SQL 依赖项通知。
我使用硬编码的命令文本成功:
using (SqlConnection conn = new SqlConnection(ConnStr))
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT [t0].[discounttype] FROM [dbo].[discounts] AS [t0]";
var dep = new SqlDependency(cmd);
dep.OnChange += OnDataChange;
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read()) { Console.WriteLine("Name = " + dr[0]); }
}
}
我看到QN: SubscriptionSQL Server Profiler 中列出了一个事件,其文本包括subscription registered. discounts之后的一切都很好 - 当对表格进行更改时,我会收到通知。
但是,如果我使用 LINQ 尝试相同的查询:
using (TestNotifyDataContext dc = new TestNotifyDataContext(ConnStr))
{
var results = from d in dc.Discounts select d;
SqlCommand cmd = (SqlCommand) dc.GetCommand(results);
var dep = new SqlDependency(cmd);
dep.OnChange += OnDataChange;
List<Discount> table = results.ToList();
foreach (var discount in table)
{
Console.WriteLine("L: " + discount.discounttype);
}
}
results正确返回,但 Profiler 中没有QN: Subscription事件(因此我不会收到更改通知)。根据http://www.simple-talk.com/sql/t-sql-programming/using-and-monitoring-sql-2005-query-notification/如果订阅注册失败,应该有一个不同文本的条目但甚至没有,所以似乎服务器甚至没有收到请求。
请谁能告诉我我做错了什么或指出我正确的方向。