Current user identity in ObjectContext.SavingChang

2019-09-19 05:42发布

问题:

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.

回答1:

If this code resides in a WCF service that you consume from your ASP.NET MVC application you could send the current username as parameter to the method you are invoking.