Executing Logic Before Save or Validate with EF Code-First Models

I'm still used to EF Code First after spending years working with Ruby ORM, ActiveRecord. ActiveRecord has always had all sorts of callbacks like before_validation and before_save where an object could be changed before it was sent to the data layer. I'm wondering if there is an equivalent technique in EF Code First for modeling objects.

I know how to set the elements of an object during instantiation, of course (set defaults, etc.), but sometimes you need to intervene at different points in the object's lifecycle.

To use a slightly contrived example, let's say I have a join table linking Authors and Plays, represented by the corresponding Authoring object:

public class Authoring
  public int ID { get; set; }

  public int Position { get; set; }

  public virtual Play Play { get; set; }

  public virtual Author Author { get; set; }


where Position represents the zero indexing of the author orders associated with this Play. (You may have one South Pacific play with two authors: Rogers at position 0 and Hammerstein at position 1.)

Let's say I wanted to create a method that was checked before saving the Authoring entry to see if there are any existing authors for the Play it was linked to. If not, it sets the position to 0. If “yes”, it will find the “Position” position of the highest value associated with this replay and increment by one.

Where would I implement this kind of logic in the first layer of the EF code model? And, in other cases, what if I would like to bulk data in the code before it gets checked for validation errors?

Basically, I'm looking for the equivalent of the Rails lifecycle hooks mentioned above, or fake it in some way at least. :)


source to share

2 answers

You can override DbContext.SaveChanges, fix there and call in base.SaveChanges (). If you do, you can call DetectChanges before fixing the error. Btw. this same issue is discussed in the DbContext Programming Entity book (ISBN 978-1-449-31296-1) on pp. 192-194. And yes, this is in the context of validation ...



You can implement IValidatableObject

. This gives you one hook:

IEnumerable<ValidationResult> Validate(ValidationContext validationContext)


And you can apply your validation logic there.

There is also an event SavingChanges

on ObjectContext

(which you can get from DbContext


You can just create a UI IDoStuffOnSave

and apply it to your objects that need to do some save logic (there is nothing out of the box)



All Articles