我有一个用于//主题信息的 Web UI,add并且edit这些delete数据保存在名为Subject
. 在该表中,有诸如Id(PK)
、SubjectCode
、SubjectName
等列Tutor
...
Id
field 是主键,总是唯一的。
SubjectCode
是一个varchar
应该是唯一的字段(值CS1001
等)
插入和更新数据时,我已经使用LINQ
(C#) 验证了唯一性,如下所示。
bool isCodeExist = DbContext.Subject.Any(record => record.SubjectCode == subject.SubjectCode);
if (true == isCodeExist )
{
// SubjectCode is already exist. Do not proceed.
return -1;
}
else
{
// Proceed...
}
这仅适用于插入。
有时更新时会出现错误,例如仅更新主题的导师姓名(或其他列)。感谢您对此的帮助。
UPDATE:更新操作的完整代码部分。
public int EditSubject(Subject subject)
{
using (SMSEntities DbContext= new SMSEntities())
{
try
{
bool isCodeExist = DbContext.Subject.Any(record => record.SubjectCode == subject.SubjectCode);
if (true == isCodeExist )
{
// SubjectCode is already exist. Do not proceed.
return -1;
}
else
{
// Create table object
Subject theSubject = new Subject();
// Assign values from the domain entity obj from param
theSubject.SubjectCode = subject.SubjectCode;
theSubject.Tutor = subject.Tutor;
theSubject.LastUpdatedDate = DateTime.Now;
// other value assignment also same....
// Save subject
DbContext.Subjects.Attach(theSubject);
DbContext.ObjectStateManager.ChangeObjectState(theSubject, EntityState.Modified);
DbContext.SaveChanges();
return 0;
}
}
catch (Exception)
{
// Log exception
throw;
}
}
}