I am using ObjectContext.SavingChanges
event to update CreatedDate/UpdatedDate columns based on the object state like this
partial void OnContextCreated()
{
//Extension of the Command Timeout to avoid processing problems.
CommandTimeout = 600; //Time in seconds
this.SavingChanges += new EventHandler(Entities_SavingChanges);
}
protected void Entities_SavingChanges(object sender, EventArgs e)
{
var addedObjects = this.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added);
foreach (var addedObject in addedObjects)
{
var propertyInfo = addedObject.Entity.GetType().GetProperty("CreatedDate");
if (propertyInfo != null)
{
propertyInfo.SetValue(addedObject.Entity, DateTime.UtcNow, null);
}
}
var modifiedObjects = this.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Modified);
foreach (var modifiedObject in modifiedObjects)
{
var propertyInfo = modifiedObject.Entity.GetType().GetProperty("UpdatedDate");
if (propertyInfo != null)
{
propertyInfo.SetValue(modifiedObject.Entity, DateTime.UtcNow, null);
}
}
}
I have two more columns CreatedUser and UpdatedUser.
Is there any way to update those using current user name from context?
Ofcource, System.HttpContext.Current
is null here as this is my separate class library project, which I access through WCF service.