Problem: In my model, I need to use callbacks to process the db entity object before any ORM event is fired. Also, I am looking for a way to apply a named-scope so I don’t need to supply certain conditions for every query. For an instance; when I use Find on dbcontext object for Items I shouldn’t need to mention active = true for each call.
Questions:
-
Is there anything comparable to callbacks methods of ActiveRecord in ASP.NET MVC (EntityFramework)? Such as: after_save, before_save, after_create, before_create, after_validation, before_validation etc.
-
Should I create a “model view” to append each query with imperative conditions? Please provide an example or resource/tutorial.
No. There are no such events / callbacks available. EF
ObjectContextoffers onlyObjectMaterializedandSavingChangesevents. First can be used to react when entity is materialized (loaded) from the database and second can be used to handle anything prior to saving changes (it is similar to overridingSaveChangesmethod).Example:
EF doesn’t offer any type of global conditions / named-scopes. You must always make sure that your query contains all conditions. For example you can create custom extension method and instead of default Find use that extension method which will add all your additional conditions
Example: