RobVious RobVious - 3 months ago 23
C# Question

BeforeSave Validation with EF Code-FIrst

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

I see the following: https://blogs.msdn.microsoft.com/alexj/2009/07/20/tip-27-how-to-implement-beforesave-validation/

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;
entity.Validate(stateEntry.State);
}
}
}


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

public class ApplicationContext : DbContext {}


How can I get this working?

Answer

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;
}