Entity Framework SaveChanges does not work

1.4k Views Asked by At

I have this piece of code but it does not work, and I do not see where id the problem.

No exception is caught.

I'm working with Entity Framework 4. The SaveChanges call does not seem do anything in the database.

try
{
    Demande_Rage_Animale editdemande = DemandeRageAnimaleDAO.First(s => s.ID == demandebean.ID);

    //frombeanTodemande(demandebean, editdemande);
    editdemande.num_rapport = "111111";

    //editdemande.EntityState.
    DemandeRageAnimaleDAO.SaveChanges();
}
catch (Exception ex)
{
    Logger.Error("==> Modifier_demande_RageAnimale : " + ex.InnerException);
}
2

There are 2 best solutions below

3
On

You must mark the entity as modified before calling SaveChanges:

DemandeRageAnimaleDAO.Entry(editdemande).State = EntityState.Modified;
DemandeRageAnimaleDAO.SaveChanges();

In older versions of Entity Framework you can use this:

DemandeRageAnimaleDAO.ObjectStateManager.ChangeObjectState(editdemande, System.Data.EntityState.Modified);

It's possible that the method shown in the question is not the full picture and perhaps the entity has become detached. In this case you can attach it back to the context, mark it as modified and call SaveChanges:

var editdemande = DemandeRageAnimaleDAO.First(s => s.ID == demandebean.ID);

// whatever happens here?

DemandeRageAnimaleDAO.Demande_Rage_Animale.Attach(editdemande);
editdemande.num_rapport = "111111";
DemandeRageAnimaleDAO.ObjectStateManager.ChangeObjectState(editdemande, System.Data.EntityState.Modified);
DemandeRageAnimaleDAO.SaveChanges();
9
On

The object context must know the state of an object to save changes back to the data source.ObjectStateEntry objects store EntityState information. The SaveChanges methods of the ObjectContext process entities that are attached to the context and update the data source depending on the EntityState of each object. For more information, see Creating, Adding, Modifying, and Deleting Objects.

In your case using EF 4.0 you need call this

_yourContext.ObjectStateManager.ChangeObjectState(editdemande, System.Data.EntityState.Modified);

with version 4.1 its done like

_yourContext.Entry(editdemande).State = System.Data.EntityState.Modified;