我有一个实体框架代码头等舱(POCO):
class Contract : IMyContract
{
...
}
interface IMyContract
{
public int DateSigned{get;}
}
为什么在客户修改合同时,我无法以这种方式拦截上下文更改操作:
void context_SavingChanges(object sender, EventArgs e)
{
foreach (ObjectStateEntry entry in
((ObjectContext)sender).ObjectStateManager.GetObjectStateEntries(
EntityState.Added | EntityState.Modified | EntityState.Deleted))
{
IMyContract myContract = entry.Entity as IMyContract;
if(myContract != null)
{
...
}
}
}
答案 0 :(得分:3)
您提到了代码优先,但同时您正在处理ObjectContext
事件并将发件人转发给ObjectContext
请改为尝试:
public class MyContext : DbContext
{
private static EntityState[] states = new EntityState[]
{
EntityState.Added,
EntityState.Modified,
EntityState.Deleted,
};
...
public override int SaveChanges()
{
// If Entires<IMyContract> doesn't work use Entries() and check type
// inside the loop
foreach(var entry in ChangeTracker.Entries<IMyContract>()
.Where(e => states.Contains(e.State))
{
...
}
}
}