Timothy Timothy - 1 month ago 9
C# Question

EntityFramework with WEB API, update all properties

I'm using EF with WEB API.
I have a PUT Method which updates a entity which already is in the db.
Right now I have this:

// PUT api/fleet/5
public void Put(Fleet fleet)
{
Fleet dbFleet = db.Fleets.Find(fleet.FleetId);
dbFleet.Name = fleet.Name;
dbFleet.xy= fleet.xy;
//and so on....
db.SaveChanges();
}


But I'm lazy and would just like to write something like:

dbFleet.update(fleet);


So I don't have to update every property by its own.

I'm sure there is a way but I could only find answers on how to do this with MVC but not when using a WEB API and not receiving the model state.

Thanks

Answer

Just found the answer...

// PUT api/fleet/5
public void Put(Fleet fleet)
{
    db.Entry(fleet).State = EntityState.Modified;
    db.SaveChanges();
}

Only thing I'm not happy with is that it doesn't update child object. Fleet has FleetAttributes which are not updated like this. But I guess I can easily loop them...

EDIT this works for me:

// PUT api/fleet/5
public void Put(Fleet fleet)
{
    db.Entry(fleet).State = EntityState.Modified;
    foreach (var item in fleet.FleetAttributes)
    {
        db.Entry(item).State = EntityState.Modified;
    }
    db.SaveChanges();
}
Comments