Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible and how create a trigger with Entity Framework Core

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()
{
}
like image 554
Bastien Vandamme Avatar asked Mar 25 '19 10:03

Bastien Vandamme


People also ask

Does Entity Framework support triggers?

Triggers. Add triggers to your entities with insert, update, and delete events. There are three events for each: before, after, and upon failure.

What is trigger in .NET core?

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.

Can we create trigger on database?

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).

Does EF6 work with .NET core?

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.


1 Answers

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()
like image 106
Belyanskiy Ilya Avatar answered Sep 28 '22 18:09

Belyanskiy Ilya