我试图隔离我的自定义实体验证逻辑。
我看到以下内容:https://blogs.msdn.microsoft.com/alexj/2009/07/20/tip-27-how-to-implement-beforesave-validation/
然而,当我尝试这个时:
public partial class ApplicationContext {
public void Validate()
{
var stateEntries = ObjectStateManager.GetObjectStateEntries(
EntityState.Added |
EntityState.Modified |
EntityState.Deleted )
.Where(e => e.Entity is IValidingEntity);
foreach (var stateEntry in stateEntries)
{
var entity = stateEntry.Entity as IValidingEntity;
entity.Validate(stateEntry.State);
}
}
}
我得到Cannot access non-static method GetObjectStateEntries in a static context
,其中ApplicationContext
是:
public class ApplicationContext : DbContext {}
我怎样才能使这个工作?
答案 0 :(得分:2)
被验证的对象是什么样的?它是否实现了IValidatingEntity?
编辑:您引用的代码来自2009年,错误不正确。在DbContext中使用类似的东西来覆盖保存之前的验证protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
{
var result = base.ValidateEntity(entityEntry, items);
// do your own validation here
return result;
}