WebDevGuy2
WebDevGuy2

Reputation: 1239

Trouble updating only specific fields using EF

Developing a MVC 5 app.

View: I have a table which is editable. I only want to update rows that have changed. Also, I only want to update 2 fields, not all of them.

Here's the viewmodel....

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; }
  }
}

Here's the update/post code...

  [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();
}

It works until the first .IsModified statment (for SurveyAnswer field). The error is...

The property 'Id' is part of the object's key information and cannot be modified.

I'm not trying to update the Id field. Any idea why this is happening or how I can get this to work correctly?

Upvotes: 0

Views: 56

Answers (1)

JuanR
JuanR

Reputation: 7783

I think this may be the result of you assigning a value to the Id property AFTER you attach the object. Assigning the Id before attaching it may yield better results but I haven't tested this.

In any event, I would recommend a different approach. If I was you, I would do the following:

  • Loop through the list.
  • Get the object from the database with EF using the key (presumably the Id field)
  • Update the two fields you are interested on.
  • Save the changes when the loop is done.

I don't know how many records you have. It may not be feasible to do this for performance reasons but that is what I would recommend if performance is not a concern.

Upvotes: 2

Related Questions