代码之家  ›  专栏  ›  技术社区  ›  Ash Machine

扩展Linq部分方法时出现SQL Server超时异常

  •  1
  • Ash Machine  · 技术社区  · 16 年前

    在.NET4.0和LINQtoSQL中,我尝试使用一个分部类来“触发”更新方法(现有的DBML方法)中的更改。为简单起见,假设一个表包含Id和Value列

    auto gen DBML包含一个方法 OnValue已更改 ,我将扩展它,作为练习,尝试更改另一行中的一个值:

       public partial class Things
        {
            partial void OnValueChanged()
            {
                MyAppDataContext dc = new MyAppDataContext();
                var q = from o in dc.GetTable<Things>() where o.Id == 13 select o;
                foreach (Things o in q)
                {
                    o.Value = "1";  // try to change some other row
                }
                try
                {
                    dc.SubmitChanges();
                }
                catch (Exception)
                {
                    // SQL timeout occurs 
                }
            }
        }
    

    发生SQL超时错误。我怀疑datacontext在当前OnValueChanged()方法处理它的datacontext之前尝试SubmitChanges()会感到困惑,但我不确定。

    大多数情况下,我找不到一个在现有DBML生成的方法中触发DB更新的好模式的例子。

    有没有人能给我一些建议,说明为什么这样做行不通,以及我怎样才能完成一些可以正常工作的事情(我意识到我可以在SQL数据库中触发,但不想走这条路。)

    谢谢!

    3 回复  |  直到 13 年前
        1
  •  3
  •   Adam Robinson    16 年前

    首先,你没有处理 DataContext 在你的职责范围内。把它包起来 using 声明。

    实际的问题来自于这样一个事实:通过设置 Value 属性。你只是在打电话之前就已经超时了 StackOverflowException .

    不清楚你想在这里做什么;如果您试图允许在设置 价值 internal 实例布尔自动属性调用 UpdatingValue true 在你的每一件衣服上 foreach 块,然后将其设置为 false 更新值之后。然后,作为第一行 OnValueChanged ,检查以确保 更新值 是 假

    这样地:

    public partial class Things
    {
         internal bool UpdatingValue { get; set; }
    
         partial void OnValueChanged()
         {
             if (UpdatingValue) return;
    
             using(MyAppDataContext dc = new MyAppDataContext())
             {
                 var q = from o in dc.GetTable<Things>() where o.Id == 13 select o;
                 foreach (Things o in q)
                 {
                     o.UpdatingValue = true;
                     o.Value = "1";  // try to change some other row
                     o.UpdatingValue = false;
                 }
    
                 dc.SubmitChanges();
             }
         }
     }
    
        2
  •  0
  •   Aaron Daniels    16 年前

    我怀疑您可能通过更改事物的OnValueChanged事件处理程序中事物的值引入了无限递归。

    对我来说,解决问题的更简洁的方法不是在DBML文件中生成类,而是使用 LinqToSql attributes 在您创建的类上。通过这样做,您可以在属性/列的setter中进行“trigger”修改。

        3
  •  0
  •   Mark Lakata    15 年前

    我也有类似的问题。我不认为这是代码中的错误,我倾向于SqlDependency如何工作的错误。我和你做了同样的事情,但是我做了逐步的测试。如果select语句返回1-100行,那么它工作正常。如果select语句返回1000行,那么我将得到SqlException(超时)。

    我的解决方案是将代码包装在一个大的try/catch块中,以捕获SqlException。如果发生这种情况,则执行相同的查询,但不使用SqlDependency,也不将其附加到命令。这不再挂起SubmitChanges调用。紧接着,我重新创建SqlDependency,然后再次进行查询,以重新注册依赖关系。

        public Constructor(string connString, CogTrkDBLog logWriter0)
        {
            connectionString = connString;
            logWriter = logWriter0;
    
            using (SqlConnection conn = new SqlConnection(connString))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand("SELECT is_broker_enabled FROM sys.databases WHERE name = 'cogtrk'", conn))
                {
                    bool r = (bool) cmd.ExecuteScalar();
                    if (!r)
                    {
                        throw new Exception("is_broker_enabled was false");
                    }
                }
            }
            if (!CanRequestNotifications())
            {
                throw new Exception("Not enough permission to run");
            }
    
    
            // Remove any existing dependency connection, then create a new one.
            SqlDependency.Stop(connectionString);
            SqlDependency.Start(connectionString);
    
            if (connection == null)
            {
                connection = new SqlConnection(connectionString);
                connection.Open();
            }
    
            if (command == null)
            {
                command = new SqlCommand(GetSQL(), connection);
            }
    
            GetData(false);
            GetData(true);
        }
    
    
        private string GetSQL()
        {
            return "SELECT id, command, state, value " +
            " FROM dbo.commandqueue WHERE state = 0 ORDER BY id";
    
        }
        void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            // Remove the handler, since it is only good
            // for a single notification.
            SqlDependency dependency = (SqlDependency)sender;
            dependency.OnChange -= dependency_OnChange;
    
            GetData(true);
        }
    
        void GetData(bool withDependency)
        {
            lock (this)
            {
                bool repeat = false;
                do {
                    repeat = false;
                    try
                    {
                        GetDataRetry(withDependency);
                    }
                    catch (SqlException)
                    {
                        if (withDependency) {
                            GetDataRetry(false);
                            repeat = true;
                        }
                    }
                } while (repeat);
            }
        }
    
        private void GetDataRetry(bool withDependency)
        {
            // Make sure the command object does not already have
            // a notification object associated with it.
            command.Notification = null;
    
            // Create and bind the SqlDependency object
            // to the command object.
    
            if (withDependency)
            {
                SqlDependency dependency = new SqlDependency(command);
                dependency.OnChange += dependency_OnChange;
            }
    
    
            Console.WriteLine("Getting a batch of commands");
            // Execute the command.
            using (SqlDataReader reader = command.ExecuteReader())
            {
                using (CommandQueueDb db = new CommandQueueDb(connectionString))
                {
                    foreach (CommandEntry c in db.Translate<CommandEntry>(reader))
                    {
                        Console.WriteLine("id:" + c.id);
                        c.state = 1;
                        db.SubmitChanges();
                    }
                }
            }
        }