script 1
The following are some recommended practices. When you use STE in a WCF script, you must rely on the change tracking that STE implements, so on the server side you do the following.
db.Users.ApplyChanges(user); db.SaveChanges();
Scenario 2 However, if you are on a server, the recommended practice is to create a method for a partial class for an objectcontext called EnableChangeTracking. This method will query for objects that are in a constant state that implements IObjectWithChangeTracker and includes change tracking, something like this
user = db.users.first(u => u.userid == 1); db.EnableChangeTracking();
now try saving the user object from a different context from which it was originally extracted from
db2.users.ApplyChanges(user); db2.SaveChanges();
scenario 3 if on the server side you are connected to the same object from which you extracted the user object, then you use STE as a simple poco object, as shown below.
user = db.users.first(u => u.userid == 1); user.LastName = "XYZ"; db.DetectChanges(); //no need for it cuz Savechanges implicitly calls this. db.SaveChanges();
scenario 4 if the user object is retrieved from another context, then the context u will use it to save, then there is another option where u puts the object as changed and do not care about what was changed.
user = db.users.first(u => u.userid == 1); var db2 = new ObjectContext(); user.LastName = "XYZ"; db2.Users.Attach(user);
scenario 5 if the user object is retrieved from another context, then the context u will use it to save, then there is another option when u retrieves the original object.
user = db.users.first(u => u.userid == 1); user.lastName ="XYZ"; var db2 = new ObjectContext(); db2.Users.First(u => u.userid == user.userid); db2.users.ApplyCurrentValues(user); db2.SaveChanges();
Here is a blog post that describes several scenarios. http://weblogs.asp.net/zeeshanhirani/archive/2010/03/30/modifying-self-tracking-entity-on-the-server.aspx
I cover these concepts extensively in my Entity Framework 4.0 recipe book with lots of scripting.