3

我尝试使用以下代码更新 sql 表中的所有记录,但没有更新数据。有谁知道为什么?

        using (DataContext db = new DataContext())
        {
            foreach (Item record in db.Items)
            {
                record.Description += "bla";
                db.SubmitChanges();
            }
        }

设置器代码:

[Column(Storage="_Description", DbType="NVarChar(400) NOT NULL", CanBeNull=false)] 
public string Description
{ 
  get { return this._Description; }
  set { 
      if ((this._Description != value))
       { 
         this._Description = value; 
       }
      }
}
4

5 回答 5

4

出于好奇,看看将 SubmitChanges() 移到循环之外是否会产生影响:

        using (DataContext db = new DataContext())
        {
            foreach (Item record in db.Items)
            {
                record.Description += "bla";   
            }
            db.SubmitChanges();
        }
于 2009-09-07T23:23:51.793 回答
3

根据您在评论中发布的设置器的详细信息,您的 Description 属性尚未正确创建以通知属性更改。您是自己编写的属性还是由 VS2008 工具生成的?

您的 Item 类(就此而言,所有 Linq to Sql 实体都应实现 INotifyPropertyChanging 和 INotifyPropertyChanged),这将为您提供 PropertyChanging 事件和 PropertyChanged 事件,如果您使用 VS2008 工具,您应该在实体类中获得如下几个方法:

    protected virtual void SendPropertyChanging(string propertyName)
    {
        if (this.PropertyChanging != null)
        {
            this.PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
        }
    }

    protected virtual void SendPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

现在,在您的属性设置器中,您应该使用这些方法来引发所需的事件:

[Column(Name="Description", Storage="_Description",
                  DbType="NVarChar(400) NOT NULL", CanBeNull=false)]   
public string Description
{
     get { return this._Description; }
     set
     {
         if ((this._Description != value))
         {
             this.SendPropertyChanging("Description");
             this._Description = value;
             this.SendPropertyChanged("Description");
         }
     }
 }

我还注意到您没有在列属性中设置 Name 属性,所以添加它以防万一(假设您的列名是“描述”,我将它包含在我的示例中)。

于 2009-09-08T00:21:10.500 回答
2

也许您需要提供一个连接字符串。

using (DataContext db = new DataContext(_MyConnectionString))
{
    foreach (Item record in db.Items)
    {
        record.Description += "bla";
    }
    db.SubmitChanges();
}

在不提供连接字符串时,DataContext 出现了一些奇怪的问题。

于 2009-09-08T00:06:09.773 回答
2

我会指出你可以在循环关闭后提交更改......这不会解决你的问题,但它会有所帮助。

于 2009-09-08T00:08:26.653 回答
0

我意识到这是一个非常古老的问题,但仍然没有答案。

Simon Fox 提供的答案在技术上是正确的,BFree 的建议可以节省大量时间。

但是,如果您的表没有在表中指定主键,则 DBML 对象将不会检测到更改并且不知道如何更新您的记录。

截屏

于 2018-06-21T21:39:26.330 回答