Im using EF4 in VS2010, POCO and model based approach.
My entity has the following properties: Id: Guid, Name: String, Created: DateTime, Modified: DateTime, Revision: Int32.
I create my object, set the name and save it to the database using the EF4 context. This should set the Id in the new Guid (works with Identity-SGP), now set in the settings, Changed to the left as null, Revision set to 0. I retrieve the object, change the name and save it again. This time, the value Modified value should be set now, and the revision should be 1.
What is the best way for me to do this using EF4 with an EDMX designer?
Update:
Here is what I ended up using:
public override int SaveChanges(System.Data.Objects.SaveOptions options) { foreach (ObjectStateEntry entry in ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified).Where(e => 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); }
What does not work...: (
The problem is that the entry.State element is still not changed, even if I explicitly run the MarkAsModified () method. I do not get it ...
Why is default change tracking not enabled? I use self-learning objects, so why would I do this and explicitly enable it every time? And why are entities stored until db, even if the state is unmodified? And what is the difference between EntityState and ObjectState? Im currently doing all the changes and updates to serveride, but I will also use the WCF service to move objects back and forth after a while ... Is there a difference in how the changes are processed here? If the server server all changes, regardless of how to make / turn off the changes, saved? I want nothing to ever be saved without updating Modified, Revision, etc. These properties should always be set on the server when the object is returned and modified. (I am not saying sql-server-side here, but server-server)
Andreas Zita
source share