SapphireDb logo SapphireDb

Server - Events

SapphireDb has different event hooks for models that can used to manipulate the behavior of the model when created, updated or removed


The event hook is an attribute that can be applied to the model class.
Available event attributes: [CreateEvent], [UpdateEvent] and [RemoveEvent]
Each event hook has three parameters. You can define a method name for every parameter.
  • before: The method will get executed before the model get's manipulated by SapphireDb
  • beforeSave: The method will get executed before the model get's stored in database
  • after: The method will get executed after the model was stored in database
  • insteadOf: The method will get executed instead of performing any operation (useful for soft delete functionality for example)
You can use dependency injection for the method. SapphireDb will provide you a HttpInformation-object with information about the request and the instances found in the DI-Container.
Event hooks of base classes get inherited and will also get executed in case of an event.


This example demonstrates the use of event attributes.
The example has 5 event-methods.
Two of the methods update the date fields when the model is created or updated.
The other methods create entries in the collection logs for each action.

\f:(csharp:EventDemo.cs) [CreateEvent(Before = nameof(OnCreate), After = nameof(OnCreated))]\n [UpdateEvent(Before = nameof(OnUpdate), After = nameof(OnUpdated))]\n [RemoveEvent(After = nameof(OnRemoved))]\n public class EventDemo\n {\n \t[Key]\n \tpublic Guid Id { get; set; }\n\n \tpublic DateTime CreatedOn { get; set; }\n\n \tpublic DateTime UpdatedOn { get; set; }\n\n \t[Updatable]\n \tpublic string Content { get; set; }\n\n \tprivate void OnCreate()\n \t{\n \t\tCreatedOn = DateTime.Now;\n \t}\n\n \tprivate void OnCreated(DemoContext demoContext)\n \t{\n \t\tdemoContext.Logs.Add(new Log()\n \t\t{\n \t\t\tContent = $"Created {Content}"\n \t\t});\n \t\tdemoContext.SaveChanges();\n \t}\n\n \tprivate void OnUpdate()\n \t{\n \t\tUpdatedOn = DateTime.Now;\n \t}\n\n \tprivate void OnUpdated(DemoContext demoContext)\n \t{\n \t\tdemoContext.Logs.Add(new Log()\n \t\t{\n \t\t\tContent = $"Updated {Content}"\n \t\t});\n \t\tdemoContext.SaveChanges();\n \t}\n\n \tprivate void OnRemoved(DemoContext demoContext)\n \t{\n \t\tdemoContext.Logs.Add(new Log()\n \t\t{\n \t\t\tContent = $"Removed {Content}"\n \t\t});\n \t\tdemoContext.SaveChanges();\n \t}\n } \f:(csharp:Log.cs) public class Log\n {\n \t[Key]\n \tpublic Guid Id { get; set; }\n\n \tpublic string Content { get; set; }\n }



This website uses Google Analytics. If you want to disable it just unselect the option: