Base solution for your next web application
Open Closed

Update only specific columns of entities supplied at runtime #3401


User avatar
0
sparkyjr created

My requirement is to update only certain columns of an Entity. The primary key, and any no of other columns from that entity will be supplied by the user, and I have to update this entity with these new values.

One solution for this is using the DBContext as mentioned [https://stackoverflow.com/a/21350893/2313371])

public static void Update(int id, string name, string family)
{
    var _person = new Person() { Id = id , Name = name };

    using (var newContext = new MyDbContext())
    {
        newContext.Persons.Attach(_person);
        newContext.Entry(_person).Property(X => X.Name).IsModified = true;
        newContext.SaveChanges();
    }
}

And the same can be made in a Generic fashion as described here [http://patrickdesjardins.com/blog/how-to-update-specific-field-of-your-entity-with-a-generic-method-and-entity-framework])

public int Update(T entity, Expression<Func<T, object>>[] properties)
{
      DatabaseContext.Entry(entity).State = EntityState.Unchanged;
      foreach (var property in properties)
      {
           var propertyName = ExpressionHelper.GetExpressionText(property);
           DatabaseContext.Entry(entity).Property(propertyName).IsModified = true;
      }
      return DatabaseContext.SaveChangesWithoutValidation();
}

and use it as

...Update(Model, d=>d.Name); //or ...Update(Model, d=>d.Name, d=>d.SecondProperty, d=>d.AndSoOn);

How can we achieve this in our ABP framework?

One way is to fetch the entity, and update necessary columns as described below

int id = 10;
string newName,newAge;
var _person = _personRepository.Get(id);

if(nameColumnModified())
  _person.Name = newName;

if(ageColumnModified())
  _person.Age = newAge;

_personRepository.Update(_person );

I want to know if there is a better way to do this, like the one mentioned above using the DBContext method?


1 Answer(s)
  • User Avatar
    0
    alper created
    Support Team

    hi

    Why don't you use DTO. Just create a new class (dto) with the properties you want to update. At your controller or application service method use this dto as parameter. When you map dto to database entity, only the properties in the dto object will be updated and rest will be the same. This is simple and good practise.

    Note: I assume you know and use dto mapping (eg: automapper)