user10612954
user10612954

Reputation:

Raw SQL in EF migration

I will be adding a Country table into a database that will be required a field for a Student - However, the Student table has records, so I want to initially set Country as nullable, run raw SQL in the migration to set the CountryId for existing students and then alter the foreign to key to be non nullable. Would this be possible? thanks

public class Country {
    public int Id {get; set;}
    public string Name {get; set;}
}

public class Student {
    public int? CountryId {get; set;}
    public virtual Country Country {get; set;}
}

Upvotes: 3

Views: 1158

Answers (2)

Robotronx
Robotronx

Reputation: 1818

I am using EF Core 8 and the method shown in the other answer is not on the base class anymore. You can do it this way:

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.Sql("INSERT INTO ...");
}

Upvotes: 0

user10612954
user10612954

Reputation:

I've managed to figure it out, the Migration class inherits from DbMigration , this gives access to the method 'Sql' that can be used to write raw sql. -

 public override void Up()
    {
        Sql("INSERT INTO Table VALUES ('val')");
        Sql("UPDATE Table SET COL = '1' WHERE COL IS NULL ");
    }

Upvotes: 3

Related Questions