更新前检查重复项

时间:2013-01-20 11:44:57

标签: linq entity-framework c#-4.0

我有一个Web UI来添加 / 编辑 / 删除主题信息,这些数据保存在名为{{的SQL Server数据库表中1}}。在该表中,有SubjectId(PK)SubjectCodeSubjectName等列...

Tutor 字段是主键,始终是唯一的。

Id SubjectCode字段,应该是唯一的(varchar等值。)

在插入和更新数据时,我使用CS1001(C#)验证了唯一性,如下所示。

LINQ

这仅适用于插入。

有时在更新时会出现错误,例如仅更新主题的教师名称(或其他列)。感谢你的帮助。

更新:更新操作的完整代码部分。

bool isCodeExist = DbContext.Subject.Any(record => record.SubjectCode == subject.SubjectCode);

if (true == isCodeExist )
{
    // SubjectCode is already exist. Do not proceed.
    return -1;
}
else
{
    // Proceed...
}

1 个答案:

答案 0 :(得分:1)

如果仅用于更新,则在谓词中也应检查Id,如下所示:

bool isCodeExist = DbContext.Subject.Any(record => 
                                         record.SubjectCode == subject.SubjectCode &&
                                         record.Id != subject.Id);

更新

但如果它是UpdateOrInsert:

public int EditSubject(Subject subject)
{
    using (SMSEntities DbContext= new SMSEntities())
    {
        try
           {                    
            var theSubject = DbContext.Subject.SingelOrDefault(record => record.SubjectCode == subject.SubjectCode);

            if (theSubject != null)
            {
                 // A subject with the same SubjectCode exists.
                 if(existingSubject.Id != Subject.Id)
                 {
                     //It's another subject.
                     return -1;
                 }// else it's the same Subject so we may want to update it.
            }
            else //Subject does not exist.
            {
                // Create table object 
                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;
        }
    }
}

如果有帮助,请告诉我。