0

I want to update a single field in ASP.Net MVC 5 I get error:

My Code:

  MyJobs.PublishStatus = 1;
  db.MyJobContext.Attach(MyJobs);
  db.Entry(MyJobs).Property(x => x.PublishStatus).IsModified = true;
  //db.Configuration.ValidateOnSaveEnabled = false;
  db.SaveChanges();

I get bellow error:

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.

there is post regarding this error but I could not figure it out: Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."

and updating single field in asp.net MVC from: How to update only one field using Entity Framework?

MJ X
  • 8,506
  • 12
  • 74
  • 99
  • 1
    `MyJobs.PublishStatus = 1;` possibly already updating `PublishStatus` if `MyJobs` coming from a LINQ result set, so that when `Attach` is executed there are no rows to be updated anymore. – Tetsuya Yamamoto Sep 04 '17 at 07:25
  • if you set `ValidateOnSaveEnabled` to false, it will work. I can see your code you already have that line, why did you comment it ? – Munzer Sep 04 '17 at 07:55
  • I tried that but didn't work – MJ X Sep 04 '17 at 08:43

1 Answers1

0

I fixed the issue by updating my form and added the input hidden for Id field

@using (Html.BeginForm())
{
     @Html.AntiForgeryToken()
     @Html.HiddenFor(model => model.Id)
     <div class="form-actions no-color">
        <input type="submit" value="Publish" class="btn btn-default" />
     </div>
}

hope this will help someone who face the same issue.

MJ X
  • 8,506
  • 12
  • 74
  • 99