Is there a nice way to execute code when an entity is being saved to the database using EF/code-first?
I have a Url property on many of my entities. If a URL has not been given explicitly, I would like to calculate one as the object is persisted, eg.:
public void OnModelSaving()
{
// If a URL has not been specified, generate one from the name.
if (this.Url == null)
{
this.Url = Helper.GenerateSafeUrl(this.Title);
}
}
Ideally, I’d like all this code to be stored inside the Model, but since I don’t have an EF-owned base/partial class, I suspect if it’s possible, I’d have to register/wire it up elsewhere. Question is – is it possible, and if so, how do I wire it up?
The only way is to override
SaveChangesmethod on your context, iterate through changed entities and check theUrlIf you have many entity types providing
Urlyou can try to define interface with thatUrlimplemented by all that entity types and inOfTypeuse that interface.