Database seeding

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Chmarkine (talk | contribs) at 03:07, 26 January 2015 (→‎External links: see here: use HTTPS for sites that require it., replaced: http://msdn.microsoft.com/en-us/libra using AWB). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Database seeding is the initial seeding of a database with data.

This is often an automated process that is executed upon the initial setup of an application.

The data can be dummy data or necessary data such as an initial administrator account.

Entity Framework

\Migrations\Configuration.cs

public class ApplicationDatabaseInitializer : DropCreateDatabaseIfModelChanges<DbContext>
{
    protected override void Seed(DbContext context)
    {
        var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
        var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

        var username = "Alice";
        var password = "password123";
        var role = "Admin";

        // Create role Admin if it does not exist
        if (!RoleManager.RoleExists(role))
        {
            RoleManager.Create(new IdentityRole(role));
        }

        // Create user Alice
        var user = new ApplicationUser() { UserName = username; };
        var result = UserManager.Create(user, password);

        // Add user Admin to role Admin
        if (result.Succeeded)
        {
            var result = UserManager.AddToRole(user.Id, role);
        }
    }
}

Laravel PHP Framework

app/database/seeds/users.php

class DatabaseSeeder extends Seeder {
    public function run()
    {
        $this->call('UserTableSeeder');
        $this->command->info('User table seeded!');
    }
}

class UserTableSeeder extends Seeder {
    public function run()
    {
        DB::table('users')->delete();
        User::create(array('email' => 'foo@bar.com'));
    }
}

External links