开发者

SqlDependency subscription is registered with hard-coded SQL command, but not with LINQ

I am trying to get SQL Dependency notifications working with LINQ.

I am successful with hard-coded command text:

   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]); }
        }
    }

I see a QN: Subscription event listed in the SQL Server Profiler with text including subscription registered. Everything after that is fine - I am notified when a change is made to discounts table.

However, if I try the same query using 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 are returned correctly but there is no QN: Subscription event in the Profiler (so I don't get notified on changes). According to h开发者_如何学运维ttp://www.simple-talk.com/sql/t-sql-programming/using-and-monitoring-sql-2005-query-notification/ there should be an entry with different text if the subscription fails to register but there isn't even that, so it seems that the request isn't even being received by the server.

Please can anyone tell me what I've done wrong or point me in the right direction.


I guess this is because two separate SqlCommand objects are created, one in dc.GetCommand(results), and one in results.ToList(); So, the actually executed SqlCommand object is not associated with the SqlDependency object.

Try cmd.ExecuteReader and see if the dependency get's registered.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜