You cannot have a context in the migration.
Logically, migrations are first started to update the database schema, then you may have a context for working with data through it. If your database does not match the model, or even the table still does not exist, you cannot use it in EF.
I had to look into the EF code (and also because it was curious). In practice, the Sql () method in the DbMigration class at several levels below simply adds an SQL string to the list of queries that must be executed in the transaction and moved. He does not fulfill it when he is called. In short, EF just populates a list of lines of code that should be executed at the end right away. And it seems right if you try to go through all the paths of what you can do with the C # code in the jump code.
The question is pretty good, unfortunately, until I found a better solution, and did not use pure ADO.
Another option is to generate additional custom SQL queries and use T-SQL more widely. For your case, when you want to insert a user and set groupId, looking by name, it can be used with internal selection:
INSERT INTO Users (Name, GroupId) VALUES ('John', RoleId = (SELECT Id FROM Roles WHERE Name = 'Admin')).
For my problem, I had to do more complicated execution: the following does the same as the AddOrUpdate method for DbSet using the IF statement:
IF EXISTS (SELECT * FROM Table1 WHERE Column1='SomeValue') UPDATE Table1 SET (...) WHERE Column1='SomeValue' ELSE INSERT INTO Table1 VALUES (...)
I found it here: http://blogs.msdn.com/b/miah/archive/2008/02/17/sql-if-exists-update-else-insert.aspx
source share