我首先使用EF 6.0代码。我在调用SaveChanges时使用ObjectContext进行检测。在此处理程序中,我试图将实体的自定义属性设置为某些特定值。一切正常,将在处理程序中更改的数据传播到数据库,但是问题在于,完成SaveChanges之后,更改后的Entity对象将恢复为之前的状态。
以下是一些代码:
首先,我有一个基类,该基类在所有实体中都用作父级:
public class MyBaseEntity
{
public int UserID { get; set; }
}
在我的DbContext中,我订阅了SaveChanges事件:
void ObjectContext_SavingChanges(object sender, EventArgs e)
{
var context = sender as ObjectContext;
if (context != null)
{
context.ObjectStateManager
.GetObjectStateEntries(EntityState.Added | EntityState.Modified)
.Foreach(p =>
{
// update the UserID with the current user ID that is provided
// through a construct for our DbContext
(p.Entity as MyBaseEntity).UserID = CurrentUserID
});
}
}
现在当我调用SaveChanges时,将发生以下情况:
var entity = new MyEntity();
entity.Name = "test";
// entity.UserID == 0 -> true
// before the save, entity.UserID will be 0 (default value)
context.SaveChanges();
// entity.UserID == 0 -> true
// after the save it will be again zero, although it was
// changed during ObjectContext.SaveChanges handler
// expected value would be entity.UserID = 102 (in case when global CurrentUserID is 102)
调用SaveChanges之后,将调用事件处理程序,并将正确的UserID插入数据库中,但是,完成SaveChanges之后,UserID将恢复为其原始值。
那么,这是错误还是设计错误,什么是解决方法?