7

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 the db.
What am I missing?

Adir
  • 1,423
  • 3
  • 19
  • 32

4 Answers4

13

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();
}
Mike Goatly
  • 7,380
  • 2
  • 32
  • 33
3

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

Community
  • 1
  • 1
Artemiy
  • 1,969
  • 14
  • 19
  • I suspect that he's not trying to add a new instance, otherwise he wouldn't be providing an id... Adir? edit: also the title is how to *update* an entity :) – Mike Goatly Dec 03 '10 at 16:03
  • I don't think that's how you query for a person then – Artemiy Dec 03 '10 at 16:05
  • I don't think he's querying for one, just updating one - the EF does support updating an entity in this way - I've just tried it and if you do reverse the 2nd and 3rd lines it works. – Mike Goatly Dec 03 '10 at 16:07
2

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();
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
1

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();
Morteza Manavi
  • 33,026
  • 6
  • 100
  • 83