Home > Mobile >  Asp.net MVC DB First Approach - Migrations
Asp.net MVC DB First Approach - Migrations

Time:09-12

For my past Asp.NET MVC projects I have used the Code First approach to create my web applications.

Here I got a new one, there is an old system with an already created SQL Server Database.

I need to recreate a system for the existing database.

So I have started to use Database First Approach.

I connected to the database and models & datasets generated according to the tables.

So I want to know If I want to add a column to the table which I used earlier, update it on the model, and do migration and update the database.

So I can't use it here, right?

If I want to change something, I have to change it from the database from the SQL server side, and then how I updated it on my project?

Personally, I found their database structure is somewhat wrong for certain cases.

But there are already 5000 data on the tables and they don't wanna lose it or they have not agreed to maintain two databases for their operations.

Ideas for this matter are highly appreciated.

CodePudding user response:

So what I have done here on my end was, that I initially created a migration before applying changes to the entities. Then after that, I removed the code inside the initial migration script. e.g.

public partial class InitialDbCreate : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {

    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {

    }
}

so that It will not re-create the entities/tables to the existing database, and you'll not have now a problem in applying new changes to your entities.

CodePudding user response:

This is a very common scenario. Microsoft calls it Code First with Existing database. You create scaffolding that builds model out of the database. You probably want to apply constraints and generally improve referential integrity in the database and scaffold the model a few times.

Once you are happy with the model - you stop making changes in the database! You are switching to Code First approach, where you make all the changes in the code, create migrations and apply migrations to the database.

I think, Database First referred to the approach in early versions of Entity Framework that created .edmx file. I don't think this approach is even possible today. Certainly, not recommended

  • Related