I have created a SQL script file with a bunch of insert’s into a table if the values do not already exist.
It’s made up with a series of:
INSERT INTO Departments (Number, [Name])
SELECT 3, 'TOPS'
WHERE NOT EXISTS (SELECT Number FROM Departments
WHERE Number = 3)
I have been asked if I can create a migration script in Visual Studio Entity Framework so that other devs can run it using EF code-first and calling the update-database
command.
I have no idea how to create a migration script to run this. Any pointers appreciated.
3
Answers
You should probably use the built in data seeding functions. Add a
.HasData
call to your dataContext file, i.e.and use the regular
Add-Migration
command to generate a migration. You could also add an empty migration and manually insertmigrationBuilder.Sql(...)
to run arbitrary sql code.See Migrations overview for a general overview of the migration concept
Based on your comment on the question, it appears that you want to be able to use already-prepared SQL code specifically. In that case, you can simply generate an empty migration and then execute some arbitrary SQL. Here’s an example migration from a current project of mine:
and here’s the
DatabaseUpdater.DataManager
class:That resource is a
string
containing SQL code.You can do basically the same thing, with or without the additional class, and the SQL can he hard-coded or whatever. You’d obviously also want to provide a rollback mechanism if at all possible. This one required manual intervention but we have others that downgrade automatically.
You can create an empty migrations
Add-Migration "My INSERT INTO"
Update-Database –your options