I would like to execute some LINQ in Up method of migrations. Problem is I don't know how can I get DbContext instance?
This is code generated by migrations add:
public partial class MyTableAddFieldTitle : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<string>( name: "Title", table: "MyTable", nullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "Title", table: "MyTable"); } } I would like to add something like that in Up method:
protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<string>( name: "Title", table: "MyTable", nullable: true); var context = ?????; //Actual code is much more complicated, but the principle is the same. foreach (var item in context.Set<DbMyTable>()) item.Title = item.SomeStringColumn; context.SaveChanges(); } Problem is how to get context instance? I tried with DI in constructor:
protected MyTableAddFieldTitle(MyContext context) { } but I get error:
MissingMethodException: No parameterless constructor defined for this object. System.RuntimeTypeHandle.CreateInstance(RuntimeType type, bool publicOnly, ref bool canBeCached, ref RuntimeMethodHandleInternal ctor)
DbContextin the migration stage as it's just being built. If you need to seed data, do it properly: learn.microsoft.com/en-us/ef/core/modeling/data-seedingTitledoesn't yet exists on database.Sqlbeing the only method allowing you to specify arbitrary SQL command(s). No LINQ, sorry.