开发者

How to update an entity without a round-trip? (EF 4)

I tried the following:

public void UpdatePlayer(int id)
{
    Player player = new Player() {ID  = id};
    player.Password = "12";
    Entities.Players.Attach(player);
    Entities.SaveChanges();
}

No change at t开发者_JS百科he db.

What am I missing?


I think it might be because you're setting the values before you attach the object - the data context will not know what fields have changed. Try:

public void UpdatePlayer(int id)
{
    Player player = new Player() {ID  = id};
    Entities.Players.Attach(player);
    player.Password = "12";
    Entities.SaveChanges();
}


attach is used for entities that already exist in the database, but you have to attach first, and then edit it, as another poster pointed out. you should use .Add instead of .Attach if you are creating new items.

FYI Entity Framework 4 - AddObject vs Attach


As already mentioned when you attach entity it is set to Unchanged state so you have to manually set the state to Modified. But be aware that setting the state for whole entity can cause update of all fields. So if your Player entity has more than Id and Password fields all other fields will probably be set to default values. For such case try to use:

Entities.Players.Attach(player);
var objectState = Entities.ObjectStateManager.GetObjectStateEntry(player);
objectState.SetModifiedProperty("Password");
Entities.SaveChanges();

You can also try setting password after attaching the entity:

Entities.Players.Attach(player);
player.Password = "12";
Entities.SaveChanges();


When you attach an entity using Attach method, the entity will go into Unchanged EntityState, that is, it has not changed since it was attached to the context. Therefore, EF will not generate necessary update statement to update the database.

All you need to do is to give a hint to EF by changing the EntityState to Modified:

Entities.Players.Attach(player);    
Entities.ObjectStateManager.ChangeObjectState(player, EntityState.Modified)    
Entities.SaveChanges();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜