我正在使用Entity Framework 4,当我尝试更新现有记录时,它会更新并插入具有相同值的新记录。
public void UpdateEmployeeEvaluationResponse(long empId, long evalId, long QuestID, string responseStr)
{
var currentResponse = this.LoadResponseByEvaluationIdAndQuestionIdAndEmployeeId(evalId,
QuestID, empId);
// response.ID = currentResponse.ID;
//currentResponse.ResponseDate = response.ResponseDate;
currentResponse.Response = responseStr;
// entities.ObjectStateManager.GetObjectStateEntry(response).SetModified();
// entities.EmployeeEvaluationResponses.Attach(response);
//// entities.ObjectStateManager.ChangeObjectState(currentResponse, System.Data.EntityState.Modified);
// //entities.EmployeeEvaluationResponses.ApplyCurrentValues(response);
ObjectStateEntry osmEntry = entities.ObjectStateManager.GetObjectStateEntry(currentResponse);
osmEntry.ChangeState(EntityState.Modified);
// //entities.ObjectStateManager.GetObjectStateEntry(currentResponse).SetModified();
// //entities.Refresh(RefreshMode.ClientWins, currentResponse);
// entities.Detach(currentResponse);
entities.SaveChanges();
}
这是load方法的实现
public EmployeeEvaluationResponse LoadResponseByEvaluationIdAndQuestionIdAndEmployeeId(long evaluationId,
long questionResponseId,
long employeeId)
{
return entities.EmployeeEvaluationResponses.Include("Employee").Include("Evaluation").Include
("QuestionResponse").Where(x => x.Evaluation.ID == evaluationId &&
x.QuestionResponse.ID == questionResponseId &&
x.Employee.Id == employeeId).FirstOrDefault();
}
嗨,我解决了它==>问题是,从其他用途中有一些缓存对象 我制作了代码来分离所有对象并且它可以正常工作......是的......还有另一个解决方案评论
public void UpdateEmployeeEvaluationResponse(long empId, long evalId, long QuestResponseID, string responseStr)
{
foreach (var item in entities.EmployeeEvaluationResponses)
{
entities.EmployeeEvaluationResponses.Detach(item);
}
var currentResponse = this.LoadResponseByEvaluationIdAndQuestionIdAndEmployeeId(evalId,
QuestResponseID, empId);
currentResponse.Response = responseStr;
entities.DetectChanges();
entities.SaveChanges();
//using (AttendanceEntities entity = new AttendanceEntities())
//{
// EmployeeEvaluationResponse responseObj =
// entity.EmployeeEvaluationResponses.Where(x => x.Evaluation.ID == evalId &&
// x.QuestionResponse.ID == QuestResponseID && x.Employee.Id == empId).FirstOrDefault();
// responseObj.Response = responseStr;
// entity.DetectChanges();
// entity.SaveChanges();
//}
}