Raw SQL in EF migration

Viewed 498

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;}
}
1 Answers

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 ");
    }
Related