c# - 数据表验证中的 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已经在数据表中。
我如何跳过检查它是否修改了同一条记录?
解决方案
你应该检查你的身份证。
//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.
推荐阅读
- reactjs - 根据 props 更新内部状态(反模式)
- javascript - Javascript:如何从脚本文件中的 html 页面调用函数
- node.js - ElasticSearch 上的 mapper_parsing_exception 错误
- prisma - prisma 是否支持地理空间查询
- angular - 尝试使用角度模板用图像填充引导轮播
- android - 从 Thread 获取 JSON 服务器应答到 AlertDialog
- java - 为返回特定范围之间的中心值的方法创建逻辑
- intellij-idea - 如何在 xml 中手动为工件指定清单文件的路径?
- c - 反转给定字符串中的每个单词
- mysql - 使用主数据库在 Spring MVC 应用程序中实现多租户?