How can I use DbContext which works with the current database (that now use in migration).
Example:
namespace Data.SqlServer.Migrations
{
[DbContext(typeof(MyDbContext))] // I want use this context
[Migration("CustomMigration_DataSeed")]
public partial class DataSeedMigration : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
// add some entities
_context.User.Add(new User());
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
Thanks for help!
Create a class for your migration configuration :
internal sealed class Configuration : DbMigrationsConfiguration<MyDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
//On true you might be losing data be aware.
AutomaticMigrationDataLossAllowed = false;
ContextKey = "Path To Your DbContext";
}
protected override void Seed(MyDbContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
Then reference this to your DbContext Class:
public class MyDbContext : DbContext
{
public MyDbContext()
: base("name=MyConnection")
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDbContext,Configuration>("MyConnection"));
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//here you can MAP Your Models/Entities
}
}
Remember if you do not want to migrate several POCOs then do not add them within your OnModelCreating Method and well comment them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With