How to add new table to existing database code first

To add a new table to an existing database using Code First in Entity Framework, you can follow these steps:

  1. Open your project in Visual Studio.
  2. In the Solution Explorer, right-click on the project and select "Add" > "New Item".
  3. In the "Add New Item" dialog box, select "ADO.NET Entity Data Model" and name it (e.g., "MyDatabaseModel.edmx").
  4. Click "Add" to create the new EDMX file.
  5. In the EDMX file, right-click on the "Entities" folder and select "Add" > "New Entity Data Model".
  6. In the "Add Entity" dialog box, enter the name of the new table (e.g., "MyNewTable").
  7. Click "Add" to create the new entity.
  8. In the EDMX file, drag and drop the new entity onto the "Entities" folder.
  9. In the "Entity Designer" window, configure the properties of the new entity (e.g., set the primary key, add columns, etc.).
  10. Save the EDMX file.

Alternatively, you can also add a new table to an existing database using Code First by creating a new class that inherits from DbSet<T> and adding it to the DbContext class.

Here is an example:

public class MyDbContext : DbContext
{
    public DbSet<MyTable> MyTable { get; set; }
    public DbSet<MyNewTable> MyNewTable { get; set; }
}

public class MyTable
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class MyNewTable
{
    public int Id { get; set; }
    public string Description { get; set; }
}

In this example, we have added a new MyNewTable class that inherits from DbSet<T> and added it to the MyDbContext class. This will create a new table in the database with the same name as the class.

To apply the changes to the database, you can use the Database.Migrate() method:

using (var context = new MyDbContext())
{
    context.Database.Migrate();
}

This will create the new table in the database and apply any necessary migrations.

Note: Make sure to update the DbContext class to include the new table and also update the OnModelCreating method to configure the new table.