How to run Seed() method of Configuration class of

2019-01-18 08:25发布

I have 2 questions:

1) How can I run Seed() method from the package-manager console without updating-database model?

2) Is there a way how to call Seed() method in the code?

Thx for any advice.

8条回答
乱世女痞
2楼-- · 2019-01-18 08:50

Answer question 1:

People would usually work around this by either:

  1. Making a temporary artificial change to the model
  2. Switching to DropCreateDatabaseAlways, with the consequence that the database is often dropped and recreated when it is not needed
  3. Manually deleting the database

reference: http://blog.oneunicorn.com/2013/05/28/database-initializer-and-migrations-seed-methods/

查看更多
聊天终结者
3楼-- · 2019-01-18 08:51

Add a new public method into the Configuration class. The new method only calls the protected method Seed:

public void RunSeed(DbContext db)
{
    Seed(db);
}

Then call the new method from eg. a unit test:

var db = new SomeDbContext();
var configuration = new Configuration();
configuration.RunSeed(db);
查看更多
4楼-- · 2019-01-18 08:56

Answering your first question. Create a Migration by running add-migration SeedOnly

Clear out all Up() and Down() code generated if there was any pending changes

public partial class SeedOnly : DbMigration
{
    public override void Up()
    {
    }

    public override void Down()
    {
    }
}

Then you can Target a Specific Migration by running update-database -TargetMigration SeedOnly in the Package Manager console

查看更多
干净又极端
5楼-- · 2019-01-18 09:01

Answering Question #2: Extract all the code from the Seed() method to another class. Then call that from within the Seed() method from the Configuration class:

    protected override void Seed(DbContext ctx)
    {
        new DatabaseSeed().Seed(ctx);
    }

Then you can call it from anywhere:

    new DatabaseSeed().Seed(new DbContext());
查看更多
放我归山
6楼-- · 2019-01-18 09:03

This is not exactly what you are looking for, but however take a look: Running Entity Framework Migrations via command line prompt This may help you or someone to forget application based database migration, because you can easily make scripts to run automatically...

查看更多
Animai°情兽
7楼-- · 2019-01-18 09:03

If you want to Update-Database --Target-Migration xxx and you are surprised as i was that seed() method has not been run, you can try to git stash all your changes, generate database from previous version using Update-Database (to last revision which runs seed() always) and git stash apply then.

It is ugly workaround but it helped me.

Btw: don't forget to stage your changes before stashing

查看更多
登录 后发表回答