Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

306
Visualizações
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 Respostas
Responde à pergunta

0

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

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda