Change only edited columns

Asked

Viewed 254 times

0

In an application I am developing, when trying to update only the fields that were changed the Entity Framework is also changing the fields that do not need.

Repository code:

public void Update(T entity)
{
   m_Context.Entry(entity).State = EntityState.Modified;            
}

Controller code:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(BlogViewModel model)
{
   if (ModelState.IsValid)
   {
      using (var context = new UnitOfWork())
      {
         var blogDomain = Mapper.Map<BlogViewModel, Blog>(model);

         blogDomain.DateEdited = DateTime.Now;

         context.BlogRepository.Update(blogDomain);
         context.SaveChanges();

         return RedirectToAction("Index");
      }
   }

   return View(model);
}

I would like a help to solve this problem.

  • 1

    You can bring the entity and change only the fields you need, the way you did it is really changed. !!!

1 answer

1


You can indicate to the Entity which properties will not have their status changed using the IsModified = false, follows an example:

public void Update(Classe minhaClasse)
{
    if (m_Context.Entry(minhaClasse).State == EntityState.Detached)
        m_Context.Set<Classe>().Attach(minhaClasse);

    m_Context.Entry(minhaClasse).State = EntityState.Modified;

    //Aqui é indicado que a propriedade nao deve ser alterada
     _context.Entry(minhaClasse).Property(p => p.DataCadastro).IsModified = false;

    m_Context.SaveChanges();   
}

I don’t know which architecture you are using and your model, so you may have to make adjustments to the example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.