Francesco
Francesco

Reputation: 964

Entity Framework object real update - no duplication

I'm trying to update an object in my database using entity framework 4.1 with code-first and SQL Server 2008. My object's class has a ID field of int type. The problem is that when I update my object and invoke SaveChanges on my DbContext so the database creates a copy of the datarow rather then update the one I already have. I don't want this, I just would like a clean update like in the old-fashioned SQL command UPDATE. How can I fix this?

 Nation nation = (nationDB.Nations.Where(m => m.name == "France")).SingleOrDefault();

 if (nation != null)
 {
   Nation modNation = nationDB.Nations.Find(nation.ID);
   modNation.Level++;
 }

 nationDB.SaveChanges();

public class Nation
{
    public int ID { get; set; }
    public int name { get; set; }
    public int level { get; set; }
}

Upvotes: 1

Views: 3599

Answers (2)

Jean Hominal
Jean Hominal

Reputation: 16796

I think that the ObjectStateManager has registered your object as being in the Added state. Try to set its status to Modified (by calling GetObjectStateEntry(Object) and checking/modifying the State property).

Upvotes: 1

Shiraz Bhaiji
Shiraz Bhaiji

Reputation: 65461

To update it you must first read it from the database, change it, then save it.

If you create a new entity in code, even with an existing key, EF will treat it as a new entity.

Upvotes: 3

Related Questions