Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 778
Adir Avatar asked Dec 03 '10 15:12

Adir


People also ask

How to Update a disconnected entity to the database in EF Core?

Entity Framework Core introduced the DbContext. Update() method which attaches the specified entity to a context and sets its EntityState to Modified. Alternatively, you can also use the DbSet. Update() method ( context.

How do you refresh entities?

In order to refresh the data entities, you click Data management workspace > Framework parameters > Entity settings > Refresh entity list in D365FO.

How to Update DbContext in entity framework?

This can be achieved in several ways: setting the EntityState for the entity explicitly; using the DbContext. Update method (which is new in EF Core); using the DbContext. Attach method and then "walking the object graph" to set the state of individual properties within the graph explicitly.


2 Answers

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();
}
like image 85
Mike Goatly Avatar answered Sep 20 '22 14:09

Mike Goatly


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

like image 40
Artemiy Avatar answered Sep 19 '22 14:09

Artemiy