Is it possible to create a SQL trigger with Entity Framework Core.
Maybe by using instruction in
protected override void OnModelCreating(DbModelBuilder dbModelBuilder)
{
}
Or simply by executing SQL statements in Migration scripts
public override void Up()
{
}
Triggers. Add triggers to your entities with insert, update, and delete events. There are three events for each: before, after, and upon failure.
Triggers are database object. Basically, these are a special type of stored procedure that is automatically fired/executed when a DDL or DML command statement related to the trigger is executed. Triggers are used to assess/evaluate data before or after data modification using DDL and DML statements.
CREATE TRIGGER (database trigger) Use the CREATE TRIGGER command to create database triggers that fire when a modification or attempted modification to an ObjectServer table occurs (or when a modification or attempted modification to a view affects a base table).
To use Entity Framework 6, your project has to compile against . NET Framework, as Entity Framework 6 doesn't support . NET Core. If you need cross-platform features you will need to upgrade to Entity Framework Core.
Laraue.EfCoreTriggers package for creating SQL triggers through fluent syntax which allows to execute insert, update, upsert, delete, insert if not exists statements after trigger has worked like this
modelBuilder.Entity<Transaction>()
.AfterInsert(trigger => trigger
.Action(triggerAction => triggerAction
.Upsert(transaction => new { transaction.UserId },
insertedTransaction => new UserBalance { UserId = transaction.UserId, Balance = insertedTransaction.Sum },
(insertedTransaction, oldBalance) => new UserBalance { Balance = oldBalance.Balance + insertedTransaction.Sum })));
This code will be translated into sql and applied to migrations using
migrationBuilder.Sql()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With