Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add database trigger with Entity Framework Code First Migrations

Tags:

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 trigger and I would like to do this with EF Migrations and not use a separate sql script for only this case (This would be confusing for clients, esp. after we convinced them that we can handle everything with EF Migrations). My trigger is straight forward and looks like tis:

CREATE OR REPLACE TRIGGER [name] BEFORE UPDATE ON myTable ... 

Is there a command to add a trigger to EF Migrations?

like image 960
StefanG Avatar asked Feb 12 '14 15:02

StefanG


People also ask

How do I code my first migration to an existing database?

Run the Add-Migration InitialCreate command in Package Manager Console. This creates a migration to create the existing schema. Comment out all code in the Up method of the newly created migration. This will allow us to 'apply' the migration to the local database without trying to recreate all the tables etc.

Can we run SQL script using code First migrations?

First you need to create a migration. Then in the generated migration file you can write your SQL.

How do I use triggers in Entity Framework?

Entity Framework has no support for triggers, although you can certainly manually execute a statement that would create a trigger, but you would need to do this after the table was created (if using migrations). Take note of his warning, however, EF will not be aware of any changes made in the trigger.


1 Answers

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]");     } } 
like image 140
Andy Brown Avatar answered Oct 11 '22 18:10

Andy Brown