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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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

Method 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.


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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x