I have a Web UI to add/edit/delete subject info and these data saved in a SQL Server database table named Subject. In that table there are columns such as Id(PK), SubjectCode, SubjectName, Tutor etc…
Id field is the primary key, always unique.
SubjectCode is a varchar field that should be unique (values such as CS1001 etc.)
When insert and update data, I have validated the uniqueness using LINQ (C#) like below.
bool isCodeExist = DbContext.Subject.Any(record => record.SubjectCode == subject.SubjectCode);
if (true == isCodeExist )
{
// SubjectCode is already exist. Do not proceed.
return -1;
}
else
{
// Proceed...
}
This works fine only for inserts.
Sometimes there are errors when update such as update only the tutor name (or other columns) for the subject. Appreciate your help on this.
UPDATE: Complete code section for update operation.
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;
}
}
}
If it’s only for update,in your predicate you should check for the Id too, something like this:
Update:
But if it’s an UpdateOrInsert :
Let me know if it helped.