Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 869
Timothy Avatar asked Jun 30 '15 13:06

Timothy


People also ask

How does DbContext change state of entity?

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.

How do I update my Entity Framework model in .NET core?

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.

Which of the following Webapi method is used to update data?

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.


1 Answers

db.Fleets.Attach(fleet);
db.Entry(fleet).State = EntityState.Modified;
db.SaveChanges();
like image 67
daryal Avatar answered Sep 21 '22 18:09

daryal