Update partial fields with Entity Framework

2

I am managing a project with MVC and EF 6.2 , in my model I have an entity that has four fields:

public class Entidad
{
  public string campo1 {get; set;}
  public string campo2 {get; set;}
  public string campo3 {get; set;}
  public string campo4 {get; set;}
}

My class of DAO has the update method as follows:

public void actualizar(Entidad entidad)
{
  using(var context = new DbContext())
  {
    context.Entry(entidad).State = EntityState.Modified;
    context.SaveChanges();
  }
}

However, when the update method is passed as an entity parameter with four fields set ( field1, field2, field3 and field4 ), the database record is updated correctly, without However, if I pass an entity with only three or two fields set (ex: field1 and field3 with their new values) the record is not updated.

Should I get the entity of BD and compare field by field if it is different and update it and then do the update?

    
asked by isaac 07.05.2018 в 02:11
source

1 answer

0

You can do it by determining which fields need to be modified

For example

public void actualizar(Entidad entidad)
{
  using (var context = new DBContext())
  {
    context.Entry.Attach(entidad);
    context.Entry(entidad).Property(x => x.campo1).IsModified = true;
    db.SaveChanges();

//En este caso, sólo campo1 se modificaría en la base de datos.

  }
}

I hope it was what you were looking for, greetings!

    
answered by 07.05.2018 в 13:26