首页 > 解决方案 > 数据表验证中的 C# 更新记录

问题描述

我有如下的数据表记录

Id  Code    Desc
 0   A       AA
 0   B       BB

当用户添加新记录时,所有 Id 在保存到数据库之前都将为零。我想验证用户在数据表中添加的不允许重复的记录。

我上课了

 Class book

  public int Id {get; set;}
  public string Code {get; set;}
  public string Desc {get; set;}
  public bool IsEdit {get; set;}

我执行以下操作

var match = BookTable.Where(r => r.Code == txtCode.Text)
if(match.Count() > 0)
{
     MessageBox.Show("Code exist");
     return;
}

如果用户双击代码 B 并将代码更改为代码 A,则会提示该消息。如果用户添加新记录并将代码键入为 A,它也会提示消息,它工作正常。

我现在面临的问题是当用户双击记录A并且只修改描述时,当点击保存时,它会说代码存在,因为代码A已经在数据表中。

我如何跳过检查它是否修改了同一条记录?

标签: c#winforms

解决方案


你应该检查你的身份证。

     //First, when you insert an object into your database, you should get the ID of your object and assign it to your gridview row. 


    //For exemple:
      var book= new Book();
      book.Code = "myCode";
      ..
      ..
      using(MyDataContext dc = new MyDataContext())
      {
        dc.Books.Add(book);
        dc.SaveChanges(); //Here, your object gets an ID if auto.
        myGridViewRow.Cells[index].Value = book.ID; //And then, you have not row without ID. 
      }


     //This code will check for a new record.
     var match = BookTable.Any(r => r.Code == txtCode.Text); 
     match will be true or false if there is a record with your txtCode.Text.        

     //And this one will check for an existing record
     var match = BookTable.Any(r => r.Code == txtCode.Text && r.ID != IDOfARecord);
     //This time match will be true if there is another record with the modified text. And thanks to r.ID != IDOfARecord condition, it will not check the modified record.

推荐阅读