Change only edited columns

0

In an application I'm developing, when trying to perform the update only on the fields that have been 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 an aid to solve this problem.

    
asked by anonymous 22.06.2018 / 00:49

1 answer

1

You can tell Entity which properties will not have their status changed using IsModified = false , here's 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 do not know which architecture you are using or your model, so it may be that you have to make adjustments to the example.     

22.06.2018 / 02:10