EF 4.3 Code First Migrations - Seed per migration

試著忘記壹切 提交于 2019-12-11 02:52:29

问题


have recently started using Code First Migrations and was wanting to seed data in each Up method.

is this possible?

Ie.

  1. Create database table
  2. Fill with data

for Drop:

  1. Delete data from joining table
  2. delete table

回答1:


Yes it is possible but you must do it through executing SQL commands. Use Sql method in both Up and Down methods of your migration to execute INSERT and DELETE SQL commands.




回答2:


public partial class DBInitializer : IDatabaseInitializer<DBContext>
{
    public void InitializeDatabase(DBContext context)
    {

        var cfg = new Migrations.Configuration();
        var migrator = new DbMigrator(cfg);

        List<string> pendingMigrations = new List<string>(migrator.GetPendingMigrations());

        foreach (string migration in pendingMigrations)
        {
            Console.WriteLine("Updating Migration:" + migration);
            migrator.Update(migration);
            Console.WriteLine("Updated Migration:" + migration);

            if (migration.Contains("AddMyProperty"))
            {
                // seed data codes
                context.SaveChanges();
            }                
        }

    }

}


来源:https://stackoverflow.com/questions/11611322/ef-4-3-code-first-migrations-seed-per-migration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!