3

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?

3
  • Which version of EF? Commented Aug 27, 2014 at 10:14
  • 2
    You could try _context.Configuration.ValidateOnSaveEnabled = false;. (before Attach) Commented Aug 27, 2014 at 10:34
  • great.. it works fine. thank you. Unfortunately I don't have reputation enough to vote. Commented Aug 27, 2014 at 10:39

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.