How to automatically update a changed property in Entity in Entity Framework 4 when saving?

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)

+6
c # entity-framework entity-framework-4 ef-model-first
source share
3 answers

Suppose your Entity type name is Product:

 partial void OnContextCreated() { this.SavingChanges += Context_SavingChanges; } void Context_SavingChanges(object sender, EventArgs e) { IEnumerable objectStateEntries = from ose in this.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified) where ose.Entity is Product select ose; Product product = objectStateEntries.Single().Entity as Product; product.ModifiedDate = DateTime.Now; product.ComplexProperty.Revision++; } 


If you want to use this code to populate a common field, such as ModifiedDate or ModifiedBy, for all of your entities, please take a look at this post:
Entity Structure - Audit Activity

By the way, StoreGeneratedPattern and ConcurrencyMode have nothing to do with this, they exist for completely different and unrelated things.

+3
source share

I personally relate to a code-based client solution. Since you are using POCOs, it would probably be easier if the object itself were updating. Update the installation attribute in the Name property to call the objectModified method, which modifies the Modified and Revision properties.

If this is undesirable due to the time difference between changing the property and the time the object was saved, you can touch the partial class on the Entities object. This will allow you to override the SaveChanges method in which you can touch your objects in the ObjectSet <T> property of the Entities object. Something like:

 public partial class YourEntities { public override int SaveChanges(System.Data.Objects.SaveOptions options) { //update your objects here return base.SaveChanges(options); } } 
0
source share

To achieve this, we can use the partial method and override the SaveChanges method.

 using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Core.Objects; using System.Data.Entity.Infrastructure; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; namespace TestDatamodel { public partial class DiagnosisPrescriptionManagementEntities { public override int SaveChanges() { ObjectContext context = ((IObjectContextAdapter)this).ObjectContext; foreach (ObjectStateEntry entry in (context.ObjectStateManager .GetObjectStateEntries(EntityState.Added | EntityState.Modified))) { if (!entry.IsRelationship) { CurrentValueRecord entryValues = entry.CurrentValues; if (entryValues.GetOrdinal("ModifiedBy") > 0) { HttpContext currentContext = HttpContext.Current; string userId = "nazrul"; DateTime now = DateTime.Now; if (currContext.User.Identity.IsAuthenticated) { if (currentContext .Session["userId"] != null) { userId = (string)currentContext .Session["userId"]; } else { userId = UserAuthentication.GetUserId(currentContext .User.Identity.UserCode); } } if (entry.State == EntityState.Modified) { entryValues.SetString(entryValues.GetOrdinal("ModifiedBy"), userId); entryValues.SetDateTime(entryValues.GetOrdinal("ModifiedDate"), now); } if (entry.State == EntityState.Added) { entryValues.SetString(entryValues.GetOrdinal("CreatedBy"), userId); entryValues.SetDateTime(entryValues.GetOrdinal("CreatedDate"), now); } } } } return base.SaveChanges(); } } } 
0
source share

All Articles