How can I create many tables in my database using EF Core migrations

I am doing a bookstore project and I first created one table for the adding book.
So I want to add login and signup pages and store to the database, but I am confused about how I can add another table or create tables related to my need using migrations. I have attached my DbContext class.

Forgive me my English is not so good. I am waiting for your answers. Thanks

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CODEwithZAKI.Data
{
    public class BookStoreContext : DbContext
    {
        public BookStoreContext(DbContextOptions<BookStoreContext> options)
            : base(options)
        {
        }

        public DbSet<Books> Books { get; set; }
    }
}

Dbcontext Class

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

For how to add a new table to the database with ef core code first, you can follow the below steps:

1.Create your new table as a model

public class Author
{
    public int Id { get; set; }

    public string Name { get; set; }

    //other properties
}

2.Add its entry in DbContext class

public class BookStoreContext : DbContext
{
    public BookStoreContext(DbContextOptions<BookStoreContext> options)
        : base(options)
    {
    }

    public DbSet<Books> Books { get; set; }

    public DbSet<Author> Authors { get; set; }
}

3.Create a new migration with the addition of Posts in Package Manager Console

Add-Migration AuthorMigration

4.Update database

Update-Database

Solution 2

To add new tables to you database using migrations is simply a matter of extending your BookStoreContext with the new sets and then running the migration commands. As an example using dotnet command.

Generate the new migration script:

dotnet ef migrations add DESCRIPTION_OF_YOUR_MIGRATION

Run the migration:

dotnet ef database update

And that’s it. Everytime you add new records to your BookStoreContext you just go through the above two commands to run the EF Core migration process.

PS For login/authentication/identity it is recommended to utilize ASP.NET Core Identity.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply