【发布时间】:2013-02-19 07:54:01
【问题描述】:
我正在使用ObjectContext.SavingChanges 事件来根据这样的对象状态更新 CreatedDate/UpdatedDate 列
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);
}
}
}
我还有两列 CreatedUser 和 UpdatedUser。
有没有办法从上下文中更新那些使用当前用户名的人?
Ofcource,System.HttpContext.Current 在这里为空,因为这是我通过 WCF 服务访问的单独的类库项目。
【问题讨论】:
-
HttpContext.Current 不会为空,因为代码位于不同的 dll 中。
-
不,HttpContext.Current 不为空,因为代码位于不同的 DLL 中。 HttpContext.Current 为 null,因为此代码在 WCF 服务中运行。
标签: asp.net-mvc-3 entity-framework httpcontext