RobVious RobVious - 2 months ago 4
C# Question

BeforeSave Validation with EF Code-FIrst

I'm attempting to isolate my custom entity validation logic.

I see the following:

However when I attempt this:

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;

I get
Cannot access non-static method GetObjectStateEntries in a static context
, where

public class ApplicationContext : DbContext {}

How can I get this working?


What does the object being validated look like? Does it implement IValidatingEntity?

EDIT: The code you are referencing is from 2009 and incorrect with bugs. Use something like this in DbContext to override validation before save

protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
    var result = base.ValidateEntity(entityEntry, items);
    // do your own validation here
    return result;