0

Currently I am using

db.Entry(incidentViolationForm).Property(j => j.Department).IsModified = false;
db.SaveChanges();

and for multiple columns

db.Entry(incidentViolationForm).Property(j => j.Age).IsModified = false;
db.Entry(incidentViolationForm).Property(j => j.Name).IsModified = false;
db.Entry(incidentViolationForm).Property(j => j.Address).IsModified = false;

Is there a way to simplify this to lessen those lines of codes if I have hundreds of columns to be set as .IsModified = false; ?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
listojay
  • 1
  • 3
  • What you should be doing is using a view model and only updating the properties you want - [What is ViewModel in MVC?](https://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) –  Dec 02 '17 at 06:02
  • No there is no simpler way. If you have hundreds of columns then you should just set the whole object to modified. – CodingYoshi Dec 02 '17 at 06:36
  • sir Stephen Muecke. i need to avoid modification on the model it self. because management changed their mind often, this is a database first approach so every time i update ef model from database all the modification from model will be gone. – listojay Dec 02 '17 at 07:11
  • @listojay. Did you not read the link? Use a view model. In the POST method you get the data model from the db based on the ID and update ONLY those properties you need. There is no need to use `.IsModified = false;`. DO NOT use data models in your view. –  Dec 02 '17 at 07:47

1 Answers1

0

Maybe you can do it a bit more easy to define like this;

    public void SetEntityAsModifiedByProperties(DbContext yourDbContext, EntityClass incidentViolationForm, string properties)
    {
        var propertyList = properties.Split(',').ToList();
        foreach (var property in propertyList)
        {
            yourDbContext.Entry(incidentViolationForm).Property(property).IsModified = false;
        }
    }

Usage

SetEntitiesAsModifiedByProperties(db, incidentViolationForm, "Age,Name,Address");
lucky
  • 12,734
  • 4
  • 24
  • 46