Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update only certain columns in DB using 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 force the context to track the entity using the Attach method on DbSet. Then set 'IsModified' = true for necessary properties. But EF tries to update every property in db table and SaveChanges() method throws exception that some properties is required and can't be empty. Though I mark only one property as modified. I'm 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)
        {
            ...
        }            
    }
}

Have you any idea?

like image 955
mykhailovskyi Avatar asked Mar 14 '26 18:03

mykhailovskyi


1 Answers

Ok, to have an answer for this question , I'll repeat @Stephen Muecke answer here :


You could try _context.Configuration.ValidateOnSaveEnabled = false; Please do not vote me, the credit is for @Stephen Muecke

like image 177
Ehsan Zargar Ershadi Avatar answered Mar 17 '26 06:03

Ehsan Zargar Ershadi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!