title: How to auto-update the Modified property on a Entity in Entity Framework 4 when saving?
body: <p>Im using EF4 in VS2010, POCO's and the model-first approach.</p>
  
  <p>My entity has the following properties: Id:Guid, Name:String, Created:DateTime, Modified:DateTime, Revision:Int32.</p>
  
  <p>I create my entity, set the name and save it to the database using the EF4-context. This should set Id to a new Guid (works with Identity-SGP), Created set to now, Modified left as null, Revision set to 0. I retrieve the entity, change the name and save it again. This time the Modified-value should be set to now and revision should be 1.</p>
  
  <p>How do I best accomplish this using EF4 with the EDMX-designer?</p>
  
  <p><strong>Update:</strong></p>
  
  <p>This was what I ended up using:</p>
  
  <pre><code>public override int SaveChanges(System.Data.Objects.SaveOptions options)
  {
      foreach (ObjectStateEntry entry in ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified).Where(e =&gt; e.Entity is EntityBase))
      {
          EntityBase entity = entry.Entity as EntityBase;
          if (entry.State == EntityState.Added)
          {
              entity.Version = new Version() { Major = 1, Minor = 0, Revision = 0 };
              entity.Created = DateTime.Now;
              if (OperationContext.Current != null) entity.CreatedBy = OperationContext.Current.ServiceSecurityContext.WindowsIdentity.Name;
          }
          else if (entry.State == EntityState.Modified)
          {
              entity.Version.Revision++;
              entity.Modified = DateTime.Now;
              if (OperationContext.Current != null) entity.ModifiedBy = OperationContext.Current.ServiceSecurityContext.WindowsIdentity.Name;
          }
      }
  
      return base.SaveChanges(options);
  }
  </code></pre>
  
  <p>Which isnt working... :(</p>
  
  <p>The problem is that the entry.State is still unmodified even if I explicitly run the MarkAsModified()-method. I dont get this...</p>
  
  <p>Why isnt change-tracking enabled by default? Im using self-tracking entities so why would I want it off and explicitly turn it on everytime? And why is entities persisted to db even if state is unmodified? And whats the difference between EntityState and ObjectState? At the moment Im making all changes and updates serverside but I will also use a WCF-service to transfer entities back and forth some time later... Is there a difference in how changes are treated here? If serverside all changes, no matter changetracking on/off, is persisted?? What I want is that nothing should ever be able to be stored without also updating Modified, Revision etc. These properties should always be set on the server when the object is received back and has changed. (Im not talking sql-server-side here but service-server-side)</p>