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
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.
Right-click anywhere on the design surface, and select Update Model from Database... In the Update Wizard, select the Refresh tab and select your table then click Finish button.
Here, we will implement PUT method in the Web API. The HTTP PUT method is used to update an existing record in the data source in the RESTful architecture.
db.Fleets.Attach(fleet);
db.Entry(fleet).State = EntityState.Modified;
db.SaveChanges();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With