I'm testing with EF 4.3 (beta)
I have some new classes which should generate db tables and columns.
From a old project i have some old tables in my schema, which i want to access via EF.
All Classes are declared. For accessing the old table, there is a poco which is mapped.
The db migrations tries to create that old table, too.
How can it set that this class/table is not part of the migration, but part of the ef model?
xxx.OnModelCreating()
{
modelBuilder.Ignore<myOldTableClass>();
}
removes the entire class from model. finally i can't use it for access via dbContext.
i like to use automatic migrations.
i try to avoid to migrate old db tables completely to EF classes. (Yes, i know there are generators for that)
there are 120 tables, which are still used by an old applications.
some new tables which are only used with EF (new app).
there are 3 common used tables.
those should not created but accessed via ef.
With EF 4.3.1 released there is built in support for this scenario. When adding classes that are mapped to existing tables in the database, use the -IgnoreChanges switch to Add-Migration.
This will generate an empty migration, with an updated meta-data signature that contains the newly added classes.
Usually this is done when starting using EF Migrations, hence the "InitialMigration" name:
Add-Migration InitialMigration –IgnoreChanges
The correct workflow in this case is creating first migration prior to adding changes (new classes), than adding new classes and after that creating new migration where you will have only new tables.
If you didn't use migrations so far the framework will generate migrations for all tables you have in the project because it believes you are creating initial migration. Once you have migration generated you can modify its source file and remove CreateTable code for old classes from Up method. The problem is you will probably have to do this in any subsequent migration.
Edit: I wrote a walkthrough for adding migrations to existing project with EF 4.3.1
Related
Last year, I rewrote a legacy application with .Net Core and EF Core, but elected not to add migrations at the time due to other limiting factors. The time has finally come where the new application can operate as the "single source of truth" for schema changes, but I'm at a bit of a loss as to the best way to move forward.
My end-goal is to have migrations that can scaffold out the entire existing database from nothing (minus the data contained within the non-lookup tables). Unfortunately, the most viable solution I've come up with so far is to build my migrations against a new, blank database. Then once the initial migration is created that matches the state of the current database, I would be able to copy over the __EFMigrationsHistory from the newly created database to the old one.
Alternatively, I can scaffold out a blank initial migration, and I could attempt to add logic in that migration to create the database from a SQL file if it did not exist.
Neither solution seems particularly "good". Aside from tools like FluentMigrator, are there any EF Core-centric approaches that can simplify creating migrations for an existing database that will need to be recreated for tests?
I had a similar issue when I wanted to squash all the existing migrations of the past 5 years (because it took forever to create a new instance). Here's how I did it:
Remove all migrations from your code, including any DbContextModelSnapshot.cs
Scaffold an initial migration: it will contain everything to create a new DB instance
Scaffold another migration, dedicated to seed the initial data (that's optional if you don't need to seed data on your newly created instance). The goal is to isolate the seed from the SQL structure.
Commit your changes
Keep the migrations, but remove the bodies of the Up and Down methods; the goal is to trick EF Core into thinking it applied those migrations
Update your existing instances with those empty migrations: nothing will be done, but the __EFMigrationsHistory table will contain them and ignore them in the future
Revert your changes, to restore the bodies of the migrations
With all those steps, you can now update your existing instances with any future migrations, yet also recreate new instances from scratch.
I am working on asp.net core and using EF. I have created database from scratch using EF. Now whenever there are changes in the database, adding new columns, or changing the type etc. Then I run the Update-datebase migration but I am getting an error for having tables and other object in database. Can someone help me what changes would I need to make in order to make the migration successful?
The compile error mentioned that the object already exists. Lets say if I have customer table that is already created in the database, when I run the script again after adding new object or modification, I am getting that error, this does make sense but what is the common practice to deal with the issue?
As described in Migrations Overview after you are evolving your models (adding properties, removing properties, editing them and etc...) you need to update your database schema, in order to do that, you are required to add a new migration.
This can be possible in the one of following ways:
via .NET CLI
dotnet ef migrations add NewMigrationName
via PowerShell
Add-Migration NewMigrationName
After adding a new migration you just need to sync the database by:
Update-Database
I have ASP.NET Project that have Entity Framework, it have its DbContext to map to their tables on DB.
Recently I added a model and perform a migration, but later I found that this project doesn't have any migrations, but have tables in DB.
So I created an initial migration with that new table, but is also including the other tables (because I had no previous migrations obliviously)
Since migrations are a requirement for this project and I cannot drop any table to start migration history from beginning, how can i safety perform a migration of my new table and keeping a right migration history?
I was thinking in to do something like this:
Delete the InitialMigration file that I created via dotnet ef add
Create a new InitialMigration with the current already created tables
(not sure how to do that) and somehow mark it as migrated.
Add the new model/table with another migration and update database.
Could you provide any help to achieve that?
I have several tables in my SQL database that are generated from POCO objects using Code First and Migrations. I also have several tables in a different Schema that are created outside of the project by another process.
How would I combine these two sets of tables in one DB Context without losing the code first migrations features and without overwriting the existing tables in the second Schema?
Pretty simple actually. Create or reverse engineer the other schema POCOs. Add any fluent config needed (or get it from reverse engineered class)
public virtual DbSet<OtherSchemaTable> OtherSchemaTable {get; set; }'
...
Create a new migration to replace your snapshot, but not update the database:
add-migration OtherSchemaAdded -IgnoreChanges
update-database
Now you can continue on with migrations for your tables and reference the other schema. As long as you don't change other schema models you are OK. If you are worried about that, another option is to use database views to reference the other schema tables (assuming no updates needed).
That means you have to take over the migrations process. I am not sure the EF team currently supports exempting certain entities from the Migration process (at least not directly). Perhaps you can the entities in question with a custom Attribute that you define. Then override the default SqlGenerator to ignore entities with this Attribute so CREATE TABLE statements are not issued for them.
Trying to grasp the big picture here. This is a Web Forms project using Identity + EF for user management. The default project contains IdentityModels file which suggests that I should add custom properties to ApplicationUser class and then use migrations to update my database. I did that and the database was generated/updated. So far so good.
Now I add a new EDMX to my project and import all my DB tables into it. This obviously brings in Identity tables into the diagram as well, which is good because I'll be adding my business domain tables and linking them to Identity tables through the model and then use migrations to update my database. Here are the questions and problems I face:
Am I using Code-First or Model-First, or a mix of both (Does such a mix work)?
Do I have more than one model in my project, namely the default Models file and the one generated by EDMX?
If I have two models, which of the model classes correspond to AspnetUsers table; the default ApplicationUser class or the AspNetUser class generated by the EDMX? I mean which of these classes will be used by migrations to update my table's structure?
Adding new properties to my ApplicationUser class doesn't seem to have any effect when I run Add-Migration and Update-database commands. It generates empty Up() and Down() functions.
Adding a new property to an EDMX entity and then trying to send it to the database through migrations throws error saying that the new property doesn't have a mapping column. Now that's obvious I know, but then how does Model-First approach send changes to the DB?
I know these are more than one questions, but they are tightly related and anyone trying to get a start will most probably face all of them, so I've gathered them in one place for future readers.
In my understanding using both EF Code-First and Model-First can add a burden of keeping them in sync. You may want to check the following sample project which uses only DbFirst approach:
https://github.com/kriasoft/AspNet-Server-Template
OK. After working with the project for a few days, I have figured out a few things that might be helpful for future readers:
As #Konstantin said, as a general rule, you should not use both code-first and model-first approaches in the same project. Personally I prefer database-first over both of them, i.e. create a database design and then import it into my EDMX model. I can then make changes to my DB design later and use "Update Model from Database..." command to refresh my model.
AFAIK, migrations cannot currently be used with EDMX models. These only work with code-first approach.
ASP.NET Identity will automatically create all required tables in your database when your website runs for the first time. You simply need to correct the connection string in your web.config file.
You should generally avoid bringing in Identity tables into your EDMX, but if you really need to do that, do not make changes to these entities through EDMX. Simply use ApplicationUser class in IdentityModels file to add custom properties to your user class.