开发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