问题描述
我想使用ObjectContext#SaveChanges()存储之前,在实体对象内调用验证函数。现在,我可以自己跟踪所有改变的对象,然后循环遍历所有的对象,并调用它们的验证方法,但是我认为一个更简单的方法是在保存每个实体之前实现ObjectContext调用的一些回调。后者可以完成吗?有没有其他选择?
I want to invoke a validation function inside the entities objects right before they are stored with ObjectContext#SaveChanges(). Now, I can keep track of all changed objects myself and then loop through all of them and invoke their validation methods, but I suppose an easier approach would be implement some callback that ObjectContext will invoke before saving each entity. Can the latter be done at all? Is there any alternative?
推荐答案
我已经弄明白了。基本上我们可以拦截ObjectContext的SavingChanges事件,并循环遍历新添加/修改的实体来调用它们的验证功能。这是我使用的代码。
I've figured out how. Basically, we can intercept SavingChanges event of ObjectContext and loop through the newly added/modified entities to invoke their validation function. Here's the code I used.
partial void OnContextCreated()
{
SavingChanges += PerformValidation;
}
void PerformValidation(object sender, System.EventArgs e)
{
var objStateEntries = ObjectStateManager.GetObjectStateEntries(
EntityState.Added | EntityState.Modified);
var violatedRules = new List<RuleViolation>();
foreach (ObjectStateEntry entry in objStateEntries)
{
var entity = entry.Entity as IRuleValidator;
if (entity != null)
violatedRules.AddRange(entity.Validate());
}
if (violatedRules.Count > 0)
throw new ValidationException(violatedRules);
}
这篇关于使用ADO.NET实体框架截取实体保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!