Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute Raw SQL on Entity Framework Migration

Tags:

I need to execute raw SQL as part of my database initialization with Entity Framework. The SQL is required to set the collation of a column and when given a context the code looks something like this

context.Database.ExecuteSqlCommand("ALTER TABLE my_table ALTER COLUMN my_column nvarchar(200) COLLATE Latin1_General_CS_AS");

The question is where to put this code? If I put it in the Seed method of Configuration.cs created by EF when I enable-migrations it'll work but I'll lose all knowledge of performing the SQL if I decide to delete the migrations and rebaseline at a later date. Ideally I want to abstract this SQL execution to another class that EF knows to execute each time I enable migrations and update the database.

I thought about using a database initializer but on further reading it appears that these are only invoked by the calling application: this shouldn't be the responsibility of the calling application - I want it to set the collation when entity framework creates the database.

How can I ensure that I execute raw SQL as part of my EF initial/baseline configuration such that I won't lose knowledge of what was done in the future (i.e. not just lumping it all into the seed method of the default Configuration.cs)

like image 498
James B Avatar asked Jul 25 '17 14:07

James B


1 Answers

void Up() {
   Sql("ALTER TABLE my_table ALTER COLUMN my_column nvarchar(200) COLLATE Latin1_General_CS_AS");
}

Another option is to do that as part of Seed method, but migrations seems more sane.

like image 198
Leotsarev Avatar answered Sep 21 '22 16:09

Leotsarev