Add database trigger with Entity Framework Code First Migrations

后端 未结 2 958
日久生厌
日久生厌 2020-12-14 03:04

I use Entity Framework Migrations for code first to control my database model. It works charming and I can handle until now everything. But now I need to add one database tr

相关标签:
2条回答
  • 2020-12-14 03:13

    Recently I faced similar problem and didn't find a solution to not write sql manually. So I wrote a little package which allows to write migrations using Ef Core entity builder 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 will be looks like

    public partial class AddTriggers : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql("CREATE FUNCTION LC_TRIGGER_AFTER_INSERT_TRANSACTION() RETURNS trigger as $LC_TRIGGER_AFTER_INSERT_TRANSACTION$ BEGIN INSERT INTO user_balances (user_id, balance) VALUES (NEW.user_id, NEW.sum) ON CONFLICT (user_id) DO UPDATE SET balance = user_balances.balance + NEW.sum; RETURN NEW;END;$LC_TRIGGER_AFTER_INSERT_TRANSACTION$ LANGUAGE plpgsql;CREATE TRIGGER LC_TRIGGER_AFTER_INSERT_TRANSACTION AFTER INSERT ON transactions FOR EACH ROW EXECUTE PROCEDURE LC_TRIGGER_AFTER_INSERT_TRANSACTION();");
        }
    
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql("DROP TRIGGER LC_TRIGGER_AFTER_INSERT_TRANSACTION ON transactions;DROP FUNCTION LC_TRIGGER_AFTER_INSERT_TRANSACTION();");
        }
    }
    

    Maybe it will be helpful for someone.

    0 讨论(0)
  • 2020-12-14 03:20

    You can just add a Sql("SQL COMMAND HERE") method call to your migration's Up method. Don't forget to also add the drop statement to the Down method. You can create an empty migration if you need, just by running Add-Migration without any changes to the model.

    public partial class Example : DbMigration
    {
        public override void Up()
        {
            Sql("CREATE OR REPLACE TRIGGER [name] BEFORE UPDATE ON myTable ...");
        }
    
        public override void Down()
        {
            Sql("DROP TRIGGER [name]");
        }
    }
    
    0 讨论(0)
提交回复
热议问题