1

So im getting this exeption "Attaching an entity of type 'TimeTrackerProjectV2.Models.Project' failed because another entity of the same type already has the same primary key value" When i try to edit data in my database through my webapplication.

Controller code:

/ GET: Projects/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        return View(Repositories.ProjectsRepository.GetProject(id));
    }

    // POST: Projects/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "IdProject,Name,Number,Active")] Project project)
    {
        if (ModelState.IsValid)
        {

            Repositories.ProjectsRepository.EditProjects(project);
            Repositories.ProjectsRepository.SaveProject();
            return RedirectToAction("Index");
        }
        return View(project);
    }

Repository code;

  public static void EditProjects(Project project)
    {

            db.Entry(project).State = EntityState.Modified;

    }
    public static void SaveProject()
    {
        db.SaveChanges();
    }

I already searched it on the internet but everyone that i found with the same exeption had it because they were using attache so it didnt really apply to my case.

Pedro Lopes
  • 479
  • 2
  • 9
  • 20
  • I'm betting this has to do with your context not getting disposed after each request. You can test this by instantiating with a `using` statement for each. See [this](https://stackoverflow.com/questions/23201907/asp-net-mvc-attaching-an-entity-of-type-modelname-failed-because-another-ent) – Steve Greene Aug 14 '17 at 14:16

1 Answers1

1

This happens because ef is not tracking your entity project, so it is assuming that this is a new entity, and it is attaching it instead of updating what you should do is, get the entity, update the values, then use entry<>.state

something like this

// Get By ID
var TheEntity = db.Projects.FirstOrDefault(x => x.ID = project.ID);
//Update Values like
TheEntity.someProperty = project.someProperty ; 
//Do it for all and then update the state of TheEntity 
db.Entry(TheEntity).State = EntityState.Modified;
Munzer
  • 2,216
  • 2
  • 18
  • 25