Database seeding

From HandWiki

Database seeding is populating a database with an initial set of data. It's common to load seed data such as initial user accounts or dummy data upon initial setup of an application.

Entity Framework

Main page: Software: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);
        }
    }
}

Entity Framework Core

public class DataSeedingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFDataSeeding;Trusted_Connection=True");

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>(entity => { entity.Property(e => e.Url).IsRequired(); });

        #region BlogSeed
        modelBuilder.Entity<Blog>().HasData(new Blog { BlogId = 1, Url = "http://sample.com" });
        #endregion

        modelBuilder.Entity<Post>(
            entity =>
            {
                entity.HasOne(d => d.Blog)
                    .WithMany(p => p.Posts)
                    .HasForeignKey("BlogId");
            });

        #region PostSeed
        modelBuilder.Entity<Post>().HasData(
            new Post { BlogId = 1, PostId = 1, Title = "First post", Content = "Test 1" });
        #endregion

        #region AnonymousPostSeed
        modelBuilder.Entity<Post>().HasData(
            new { BlogId = 1, PostId = 2, Title = "Second post", Content = "Test 2" });
        #endregion

        #region OwnedTypeSeed
        modelBuilder.Entity<Post>().OwnsOne(p => p.AuthorName).HasData(
            new { PostId = 1, First = "Andriy", Last = "Svyryd" },
            new { PostId = 2, First = "Diego", Last = "Vega" });
        #endregion
    }
}

Symfony PHP Framework

Main page: Software:Symfony

AppBundle/DataFixtures/ORM/customer.yml (as in Version 1 of hautelook/AliceBundle )

AppBundle\Entity\User:
  customer_{1..10}:
    username: <username()>
    email: <safeEmail()>
    plainPassword: theLetterA
    roles: [ROLE_SUPER_ADMIN]
    enabled: true

Laravel PHP Framework

Main page: Software:Laravel

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