mohammadrezamajd
mohammadrezamajd

Reputation: 149

How to set State to Modified after using Find() method in Entity Framework

I want to modify entity after using Find method but it throws error :

Attaching an entity of type 'Models.Pages' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

Code:

 media = db.Pages.Find(page.PageID).Media;
.
.
.
db.Entry(page).State = EntityState.Modified;
  db.SaveChanges();

(page is posted from view)

Upvotes: 1

Views: 1100

Answers (2)

IndieTech Solutions
IndieTech Solutions

Reputation: 2539

Instead of directly setting state, try to do the following:

//db.Entry(page).State = EntityState.Modified;



    db.Attach(page); 
    db.Entry(page).State = EntityState.Unchanged; 

    media = db.Pages.Find(page.PageID).Media;
    .
    .
    .
    db.Entry(page).State = EntityState.Modified;


    db.SaveChanges();

MS link

Edit 1 : Try to avoid tracking the first DBSet by using .AsNoTracking method:

Media = db.Pages.AsNoTracking().Find(page.PageID).Media;

Upvotes: 1

faby
faby

Reputation: 7566

I think that the problem could be that you haven't released the first dbContext, in this way you are creating two references of the same entity and you'll get the error.

You should do something like this

Media test;
//1. Get your element
using (var db1 = new MediaDBEntities())
{
  test = db1.Pages.Find(page.PageID);
}

//2. do other operations


//now save using new Context
using (var db2 = new SchoolDBEntities())
{
  //3. Mark entity as Unchanged
   db2.Entry(test).State = System.Data.Entity.EntityState.Unchanged;     

   //4. call SaveChanges
   db2.SaveChanges();
}

Upvotes: 0

Related Questions