seeding asp core 3.1 code example

Example: database hasData method C#

// it goes into class ApplicationDbContext : DbContext
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Author>().HasData(
        new Author
        {
            AuthorId = 1,
            FirstName = "William",
            LastName = "Shakespeare"
        }
    );
    modelBuilder.Entity<Book>().HasData(
        new Book { BookId = 1, AuthorId = 1, Title = "Hamlet" },
        new Book { BookId = 2, AuthorId = 1, Title = "King Lear" },
        new Book { BookId = 3, AuthorId = 1, Title = "Othello" }
    );

   /*further relational instructions may come here, like:
        modelBuilder.Entity<Author>()
        .HasMany<Book>(a => a.Books)
        .WithOne(b => b.Author)
        .HasForeignKey(b => b.AuthorId);
}

Tags:

Misc Example