Add new Table to DbContext

Ronald Rex 101 Reputation points
2022-10-10T00:56:24.717+00:00

Hi friends thanks for any help. But I have injected a DbContext into my controller. Since then I have added a new table to the Database that I am using with my DbContext, so obviously in my controller I dont see the new Table as a Dbset in my DbContext. How do I add the new table? Should I use migrations or do I need to add the DbSet to the DbContext Class? Thanks !!!

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
701 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,196 Reputation points
    2022-10-12T23:05:43.48+00:00

    For Code First, consider using EF Power Tools extension for Visual Studio. It's much easier than using conventional scaffolding via a user interface and when there are changes remembers what is in your project and what is not e.g. new table, new columns. This is my approach, very rather I use migrations as the database and tables are created in SSMS.

    0 comments No comments

  2. Laxmikant 216 Reputation points
    2022-10-13T02:05:10.353+00:00

    use -Force as shown below

    Scaffold-DbContext "<connection string>"
    -Provider Microsoft.EntityFrameworkCore.SqlServer
    -Force

    for more details see - entity-framework-core-database-first-tutorial

    0 comments No comments

  3. Zhanglong Wu-MSFT 261 Reputation points Microsoft Vendor
    2022-10-19T07:13:27.693+00:00

    @Ronald Rex ,

    For entity framework core, it provides two primary ways of keeping your EF Core model and database schema in sync. as you mentioned, using code first, sync EF Core model to be the source of truth, use Migrations. As you make changes to your EF Core model, this approach incrementally applies the corresponding schema changes to your database so that it remains compatible with your EF Core model.

    here is the doc about entity framework core migrations.

    Migrations Overview

    1. Install the EF Core command-line tools:
    2. Create your first migration
    3. Evolving your model

    Best regards,
    Zhanglong

    0 comments No comments