Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

304
Views
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

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

db.Fleets.Attach(fleet);
db.Entry(fleet).State = EntityState.Modified;
db.SaveChanges();
over 4 years ago · Santiago Trujillo Report

0

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();
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!