我正在尝试使用LINQ处理SQL依赖关系通知。SqlDependency订阅使用硬编码的SQL命令注册,但不使用LINQ
我成功通过硬编码命令文本:
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]); }
}
}
我看到在SQL Server事件探查文本包括subscription registered
上市QN: Subscription
事件。之后的一切都很好 - 当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
正确返回,但没有QN: Subscription
事件探查器(所以我没有得到上进行更改通知)。根据http://www.simple-talk.com/sql/t-sql-programming/using-and-monitoring-sql-2005-query-notification/,如果订阅无法注册,但应该有不同文本的条目,但甚至没有,因此看起来该请求甚至没有被服务器接收。
请任何人都可以告诉我我做错了什么或指向正确的方向。
谢谢!是的,就是这样。我已经用'List表替换了'List table = results.ToList();';使用(SqlDataReader dr = cmd.ExecuteReader()) { table = dc.Translate (dr).ToList(); }' –
MartinC
2011-04-16 21:01:55