views:

97

answers:

1

In the "SavingChanges" event of the Entity Framework context, is there a way to ignore any changes that were made to a specific field/property?

Specifically, I have a property on my entity "CreatedBy". I need to set this property in the application, but once it is set (when the entity state is "Added"), I want the property to be available, but do not want anybody to be able to change the value.

Does anyone know how to ignore changes to this field?

Thanks.

+1  A: 

This code in the "SavingChanges" event handler seems to take care of it.

foreach (ObjectStateEntry entry in ((ObjectContext)sender).ObjectStateManager.GetObjectStateEntries(EntityState.Modified))
        {
            if (!entry.IsRelationship)
            {
                if (entry.GetModifiedProperties().Count(p => p == "CreatedBy") > 0)
                {
                    Guid cb = entry.OriginalValues.GetGuid(entry.OriginalValues.GetOrdinal("CreatedBy"));
                    PropertyInfo createdBy = entry.Entity.GetType().GetProperty("CreatedBy");
                    createdBy.SetValue(entry.Entity, cb, null);
                }
                if (entry.GetModifiedProperties().Count(p => p == "CreatedDate") > 0)
                {
                    DateTime cd = entry.OriginalValues.GetDateTime(entry.OriginalValues.GetOrdinal("CreatedDate"));
                    PropertyInfo createdDate = entry.Entity.GetType().GetProperty("CreatedDate");
                    createdDate.SetValue(entry.Entity, cd, null);
                }
            }
        }
Sako73