Updating only specific columns in db with Entity Framework

I have an entity that I know already exists in the database, but which is not currently being tracked by the context. I am forcing the context to track an object using the Attach method on the DbSet. Then set 'IsModified' = true

for the required properties. But it EF

tries to update every property in the db table, and the method SaveChanges()

throws an exception that some properties are needed and cannot be empty. Though I only mark one property as changed. I am using EF v.6.0.

Here is my code:

public bool ChangeState(int id, bool state)
    {
        try
        {
            var obj = new T {ID = id, Hidden = state};

            _context.Set<T>().Attach(obj);

            _context.Entry(obj).Property(x => x.Hidden).IsModified = true;
            return _context.SaveChanges() == 1;
        }
        catch (DbEntityValidationException dbEx)
        {
            ...
        }            
    }
}

      

Do you have any ideas?

+3


source to share


1 answer


Okay, to answer this question, I'll echo @ Stephen Muecke's answer here:




You can try _context.Configuration.ValidateOnSaveEnabled = false;

Please don't vote for me, credit to @Stephen Muecke

+1


source







All Articles