gpt4 book ai didi

c# - ObjectStateManager Changed 不会为修改后的实体触发?

转载 作者:太空狗 更新时间:2023-10-30 01:25:17 29 4
gpt4 key购买 nike

这是我在 MyObjectContext 类构造函数中所做的:

ObjectStateManager.ObjectStateManagerChanged += ObjectStateManagerObjectStateManagerChanged;

这是处理程序:

private void ObjectStateManagerObjectStateManagerChanged(object sender, System.ComponentModel.CollectionChangeEventArgs e)
{
if (e.Element is MyClass)
{
var entity = e.Element as MyClass;

var state = ObjectStateManager.GetObjectStateEntry(e.Element).State;
if (e.Action == CollectionChangeAction.Add && state == EntityState.Added)
{
//this is working fine and all created entities 100% hit this point

}

//none of the below is ever resolves to true,
//and I need to be notified on each modified entity
if (e.Action == CollectionChangeAction.Add && state == EntityState.Modified)
{

}
else if (e.Action == CollectionChangeAction.Refresh && state == EntityState.Modified)
{

}
}
}

最后做以下测试:

        var context = new MyObjectContext();
context.SetMergeOption(MergeOption.OverwriteChanges);
var company = new Company
{
Label = "Label",
};
context.Add(company);

context.SaveChanges();


company.Label = company.Label +" and so on";
context.Update(company);
context.SaveChanges();

它不会触发有关更新公司实体的事件。我如何确保它确实如此?更有趣的是,该公司包含在返回的实体列表中:

        IEnumerable<ObjectStateEntry> changedEntities =
ObjectStateManager.GetObjectStateEntries(EntityState.Modified);

MyObjectContext.SaveChanges() 方法中调用。

有人知道为什么不为更新的实体调用 ObjectStateManagerChanged 吗?或者如何以其他方式实现类似的功能?

最佳答案

因为此事件仅在 ObjectStateManager 更改时才会触发,而不会在实体更改时触发。这意味着仅当您从跟踪中附加、插入或删除实体时才会触发该事件,但如果您更改已跟踪实体的状态则不会触发该事件。在MSDN中直接描述.

如果您想对实体中的更改使用react,您必须自己实现它,例如通过在实体类型上实现 INotifyPropertyChanged

关于c# - ObjectStateManager Changed 不会为修改后的实体触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7236539/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com