Entity Framework object real update - no duplication
I'm trying to update an object in my database using entity开发者_Python百科 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; }
}
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.
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).
精彩评论