.Attach() really only useful for updating objects in a separate script like this:
User entity = null; using (var db = new DbContext()) { entity = (from p in db.Users where p.id == 1 select p).FirstOrDefault(); System.Diagnostics.Trace.WriteLine(entity.Name); //Outputs "Jane Doe" } entity.Name = "John Doe" //Modified while no longer connected to database using (var db = new DbContext()) { db.Users.Attach(entity); db.Entry(entity).Property(a => a.Name).IsModified = true; db.SaveChanges(); System.Diagnostics.Trace.WriteLine(entity.Name); //Now outputs "John Doe" }
In your scenario, the object you are creating is not retrieved by this key, and the database considers it as a completely new entity. I assume that your password is a non-zero field, and therefore EF throws an error when trying to save your changes. If you did not have such errors, EF would automatically delete any fields that you did not modify, and then save the object (which is not the result you are looking for).
To make the changes you are looking for, you probably have to do something like the following:
using (var db = new DbContext()) { db.Users.Single(a => a.id == 1).OnlineStatus = (sbyte)status; db.SaveChanges }
And then add any other error handling / checking code you want. Alternatively, you can save the object in a variable to make changes to more than one field at a time. EF should automatically detect which values ββhave been changed, and only generate the SQL necessary to make those changes. This means that if you have something like:
foreach (var item in entityList) { var entity = db.Users.Single(a => a.id == item.id); entity.Name = item.Name; entity.Address = item.Address; }
Someone will correct me if I am wrong, but EF should only update entities / fields that this code really affects. If the name or address remains the same, EF will skip this field for this object when it saves the changes to the database.
source share