EF6, migration of code-first-approach on exisitng database - c#

I have a created two separate C# web application using EF6 (one with Database First and other with Code First approach). everything is going on smoothly but after sometime it is required to merge both.
After merging , Database is same for Code First Approach.
Initial I was using 'MigrateDatabasetoLatestVersion' for database initializer.
So when I try to run my application , it throws error related to Table is already exist. I have also tried with Package manager console to update migration and it throws same error.
and so I was not able to run the new solution on same database.
For resolving this issue, I have changed database initializer to 'CreateDatabaseifNotExist'. and after that I am able to use this database with my new solutions.
But the Problem arise, when I tried to add a new column to existing table or Creating a new table with Code First approach. Since there is no migration so it skips to alter/add table and for that I have to manually run Alter/Add table Script with each changes.
Is there any valid solution for this?
either MigrateDatabasetoLatestVersion doesn't throw exception or it is not required to run db script each time.
Thanks.

Related

How does ASP.NET MVC Integrated Identity projects create tables once and only once?

When you create a new ASP.NET MVC project with Integrated Identity, on the first run the app will create the necessary tables in the database given in the connection string.
However, this happens once, and only once. When I delete all AspNetXXX tables and table _MigrationHistory, these tables are not re-created anymore. When started, the app throws an exception that the tables are missing. When I created a new app from the template and set its connection string to the same existing database, the new app recreated the tables for me, and the first one resumed operation properly.
My questions are:
How does this project / EF know to create the ASP.NET identity tables only once and where does it store the information that this app has already created its tables?
Is there a way to "reset" this for an existing project and have it re-create the tables, without activating EF Code First Migrations?
Try using the DropCreateDatabaseIfModelChanges database initializer.
It's nicely included in this tutorial: https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application (search for "DropCreateDatabaseIfModelChanges" on the page).
However, consider, that you should use that only during the actual development - because if there is some difference between your model and database, whole database will be dropped and created again.
If you want to be sure, that tables are populated with some data, use Seed() method (also in the tutorial).

Entity Framework code-first and existing database

I'm working on an application with asp.net mvc that supports install, remove plugins.
When I want to install a new plugin I have an Install method that registers new routes and ...
For database, I use a code-first approach for creating database and every plugin has it's own context class.
My question is: when I want to install a new plugin, I need to create additional tables in my existing database, or create a new database if the database does not yet exist. And if those tables are already there, nothing should be created.
How do I achieve this?
Thanks in advance
Code First Migrations has two primary commands that you are going to become familiar with
Add-Migration will scaffold the next migration based on changes you
have made to your model since the last migration was created
Update-Database will apply any pending migrations to the database
When you develop a new application, your data model changes frequently, and each time the model changes, it gets out of sync with the database. You have configured the Entity Framework to automatically drop and re-create the database each time you change the data model. When you add, remove, or change entity classes or change your DbContext class, the next time you run the application it automatically deletes your existing database, creates a new one that matches the model, and seeds it with test data.
This method of keeping the database in sync with the data model works well until you deploy the application to production. When the application is running in production it is usually storing data that you want to keep, and you don't want to lose everything each time you make a change such as adding a new column. The Code First Migrations feature solves this problem by enabling Code First to update the database schema instead of dropping and re-creating the database.
I recommend to have look following link which makes you more clear about your problem.
https://msdn.microsoft.com/en-us/data/jj591621

Run entity framework code first migration on different database

I am using EF code first to create my database, the application is in production and test now so I need to run migrations to update the database as my model changes.
I have set up migrations based on the standard instructions and it works fine, against dev database one. I also have a second database that I want to bring in line with the current code base but this second database is in an unknown state.
What I want to know is can I generate a migration class against a different database and how do I do that? I can't seem to generate a migration class against anything other than the original database I specified when I set up migrations. I have changed the DB name in the app.config but it still looks at the original database when doing migrations.
How can I explicitly specify which database to generate the migration script against?
Migrations don't look at the database other than to check if a migration has been applied (__MigrationHistory). When you setup migrations it takes a snapshot of the code models and uses that when moving forward. So if you want to bring a database in an unknown state under migration control you will need to get it to match the code model.
You could do something similar to this: Create an idempotent script from your current database (update-database -Script –SourceMigration $InitialDatabase). This will be the equivalent of all migrations needed to create and bring your database current. Since you have an existing database where some of these objects exist, you will need to manually adjust the script by removing the code for items that already exist. Once you get it to apply, you should have a database that matches your model with a populated __MigrationHistory table.
Another option is to use a schema compare utility to make the databases match and then just copy the __MigrationHistory table over.
See Migrations Under the Hood.

EntityFramework 6 Migrations for both existing and new databases?

In our software, we have a customer base with existing databases. The databases are currently accessed via EntitySpaces, but we'd like to switch to EntityFramework (v6), as EntitySpaces is no longer supported. We'd also like to make use of the migrations feature. Automatic migrations are disabled, since we only want to allow database migration to an admin user.
We generated the EF model from an existing database. It all works pretty well, but the real problem we have, is, programmatically distinguishing between existing databases that match the model but have not yet been converted to EF (missing MigrationsHistory table), and empty/new databases. Converting existing databases works well with an empty migration, but for new databases we also need a migration containing the full model. Having an initial migration in the migration chain always clashes with existing databases. Of course we could create a workaround with external SQL scripts or ADO commands, creating and populating the MigrationsHistory table. But that is something we'd like to avoid, because some of our clients use MsSql databases, some use Oracle. So we'd really like to keep the abstraction layer provided by EF.
Is there a way to get EF to handle both existing, and new databases through code-based migrations, without falling back to non-EF workarounds?
My original suggestion was to trap the exception raised by CreateTable, but it turns out this is executed in a different place so this cannot be trapped within the exception.
The simplest method of proceeding will be to use the Seed method to create your initial database if it is not present. To do this...
Starting from a blank database, add an Initial Create migration and grab the generated SQL
Add-Migration InitialCreate
Update-Database -Script
Save this script. You could add it to a resource, static file or even leave it inline in your code if you really want, it's up to you.
Delete all of the code from the InitialCreate migration (leaving it with a blank Up() and Down() function). This will allow your empty migration to be run, causing the MigrationHistory table to be generated.
In your Migration configuration class, you can query and execute SQL dynamically using context.Database.SqlQuery and context.Database.ExecuteSqlCommand. Test for the existence of your main tables, and if it's not present, execute the script generated above.
This isn't very neat, but it's simple to implement. Test it well, as the Seed method runs after EVERY migration runs, not just the initial one. This is why you need to test for the existence of a main table before you do anything.
The more complicated approach would be to write a "CreateTableIfNotExists" method for migrations, but this will involve use of Reflection to call internal methods in the DbMigration class.

how to detect the new database when change database in asp.net mvc4

The problem that when i change the new database then application not detected the new database and retreive error
The model backing the 'DBContext' context has changed since the
database was created. Consider using Code First Migrations to update
the database (http://go.microsoft.com/fwlink/?LinkId=238269).
but i don't using Migrations so i don't update-database by Package Manager Console
How can i fix this problem?
Actually it does detect changes in your database. The database differs from the model. The error message.
This error is thrown when the hash stored in the migrations history table does not match a calculated hash. (Have a look at __MigrationHistory table, might be under system tables)
If you delete this table the check is essentially disabled. You can achieve something similar by adding Database.SetInitializer<YourContextType>(null) to the startup of your application. The latter disables database creation from within that application, so if you want to create the database by code, you would need to do this from a separate application (for example an console app). I prefer to go this way for web applications.
Secondly: if you change your database manually (change columns, add tables, etc.) you need to adjust your model. So for each DDL statement, change your code.
If you are not using code first, you could update your existing model in the designer.
I ran into this problem when I first started with code first and mvc. the answer below is absolutely correct but you should go to the ASP.net website and do some tutorials on code first migrations. you need a better understanding how update database and initialize and migrations work.

Categories