If you have an entity that, as you know, already exists in the database, but which is not currently tracked by the context, as is your case, then you can specify the context for tracking the object using the Attach method on DbSet . So, in short, what the Attach method does is keep track of the entity in context and change its state to Unchanged . When you change a property after this, the tracking changes will change their state to Modified for you. In the case where you expand above, you explicitly indicate that the state is Modified , but also attaches the entity to your context. A detailed explanation can be found in.
When should you use the Attach method?
If you have an entity that you know already exists in the database, but want to make some changes:
var entity= new Entity{id=1}; context.YourDbSet.Attach(entity);
Same:
context.Entry(entity).State = EntityState.Unchanged; // Do some change... entity.value=5; context.SaveChanges();
When should you explicitly change the state of an object to Modified?
If you have an entity that, as you know, already exists in the database, but the changes have already been made. Same scenario of your example
source share