0

I need to add sql scripts to a new database created with code first approach. I couldn't find anything about that when googling for it. How is it done please?

Background:

I need to add triggers to the database that need to run everytime certain tables are updated (which is an external process not controlled by my application). So I need to install the triggers in the database on its creation.

Edit (09/16/22 3:34 pm)

Using a migration is not desired. Everything needs to be done in the code, which will already create the database if it is not present.

Edit (09/16/22 4:31 pm)

The script is not meant to be executed when the server starts. It's a trigger the db server should execute whenever a table gets changed (externally). So an ExecuteSqlRaw() call during startup of the server is not what I am looking for.

Razzupaltuff
  • 2,250
  • 2
  • 21
  • 37
  • Check this [How to run SQL scripts in a file using EF Core migrations?](https://mycodingtips.com/2021/9/20/how-to-run-sql-scripts-in-a-file-using-ef-core-migrations) – Svyatoslav Danyliv Sep 16 '22 at 10:40
  • Thing is, I need to add triggers to the database that need to run everytime certain tables are updated (which is an external process not controlled by my application). So I need to install the triggers in the database on its creation. – Razzupaltuff Sep 16 '22 at 10:53
  • What is the problem then? Add initial migration with all tables, then add another migration which add triggers. – Svyatoslav Danyliv Sep 16 '22 at 10:58
  • Everything needs to be done in the code, not via a migration. – Razzupaltuff Sep 16 '22 at 13:36
  • `db.Database.ExecuteSqlRaw(loadedSQL)` - execute this command for every SQL script. Note that `GO` divider should be processed [additionally](https://stackoverflow.com/questions/40814/execute-a-large-sql-script-with-go-commands). – Svyatoslav Danyliv Sep 16 '22 at 14:13
  • The sql script should not be executed by the app. It needs to be installed or inserted into the db. It's a trigger that the db server should execute whenever certain tables are changed. – Razzupaltuff Sep 16 '22 at 14:31
  • *It needs to be installed or inserted into* - I have missed your point. Database created by code, but scripts should not be executed by code. Triggers are SQL scripts, just execute them once and triggers will appear in database. – Svyatoslav Danyliv Sep 16 '22 at 14:37

0 Answers0