開發MVC 5應用程序。使用EF僅更新特定字段時遇到問題
查看:我有一個可編輯的表格。我只想更新已更改的行。另外,我只想更新2個字段,而不是全部。
這裏的視圖模型....
namespace SurveyingApp.ViewModels
{
[NotMapped]
public class SurveyResultsViewModel
{
// ------ hidden
public int EventId { get; set; }
[Display(Name = "Question")]
public string SurveyQuestionText { get; set; }
[Key]
public int Id { get; set; } // SurveyResults.Id
[Display(Name = "Answer")]
public string SelectedSurveyAnswer { get; set; }
public string Comments { get; set; }
}
}
這裏的更新/郵編...
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(
[Bind(Include = "Id,SelectedSurveyAnswer,Comments")]
List<SurveyResultsViewModel> mySurveyResult)
{
if (ModelState.IsValid)
{
for (int i = 0; i < mySurveyResult.Count() - 1; i++)
{
SurveyResult surveyResult = new SurveyResult();
//Attach the instance so that we don't need to load it from the DB
db.SurveyResults.Attach(surveyResult);
//Set the Id for my model.
surveyResult.Id = mySurveyResult[i].Id;
//update field from the VM
surveyResult.SurveyAnswer = mySurveyResult[i].SelectedSurveyAnswer;
surveyResult.Comments = mySurveyResult[i].Comments;
//Specify fields that should be updated.
db.Entry(surveyResult).Property(x => x.SurveyAnswer).IsModified = true;
db.Entry(surveyResult).Property(x => x.Comments).IsModified = true;
db.SaveChanges();
return RedirectToAction("Index");
}
db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
它的工作原理,直到第.IsModified statment(用於SurveyAnswer場)。錯誤是...
屬性'Id'是對象的關鍵信息的一部分,無法修改。
我不想更新Id字段。任何想法爲什麼會發生這種情況,或者我如何才能使其正常工作?
我認爲Id是外鍵,它被設置爲自動增量,因此它會自動設置您不需要設置Id值的值。 – 2017-04-17 17:34:32