Current user identity in ObjectContext.SavingChanges

£可爱£侵袭症+ 提交于 2019-12-12 04:38:22

问题


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.



来源:https://stackoverflow.com/questions/14952457/current-user-identity-in-objectcontext-savingchanges

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!