Combining Code First tables and existing tables in one context? - c#

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.

Related

How to remove the tables and migration records for an EF6 DbContext?

I am writing a service that will decide at some point it needs to store values and so needs to create tables inside an existing database. Later on, it will decide it no longer needs this storage and so should remove those tables. This cycle could repeat multiple times. I am using EF6 to simplify the database operations.
Creating the tables is easy as the first time the DbContext is used it will automatically create the tables along with the initial migration record. To avoid having to create verbose migration classes I just derive from a class from DbMigrationsConfiguration and then set the AutomaticMigrationsEnabled to true. Then it generates the tables using the code first model classes.
The problem is that later on I need to remove these tables and the matching migration record. There does not seem to be any useful method for doing that. The closest I found was DbContext.Database.Delete(). This is not appropriate because it attempts to delete the entire database and this is not possible because the database has lots of other tables used for other purposes.
Is there no way to tell EF6 to remove all the tables and migration record for a DbContext? That seems a strange omission. I do not want lots of zombie tables lingering that are no longer needed. Not everyone can create and delete an entire database to support a single DbContext.

How to change models without losing data in production in Entity Framework 6 Code-First?

I'm using Entity Framework 6 Code-First and my application is in production. I have to perform some changes in my models without lose any data.
I have to perform changes like these:
Change a relationship of two entities, from one-to-many to many-to-many.
Change an entity property's data type.
I need something like the Seed Database, but I need to load the data before change the model to later insert it again... I need to move the data. When I change the relationship I don't lose the data but the relation do.
How can I do this process?
Thanks so much for any help.
I would suggest you follow these steps:
create temporary tables that represent the data & relationships of the affected tables. Ensure you do this outside of EF, using CREATE TABLE sql
BEFORE running Update-Database, run a script to move data from the tables in question to your temp tables
Run Update-Database
Run script to insert data and relationships back into your new tables
Drop temp tables

Entity Framework 6 Migrations - Generates "SchemaName"."TableName"

I'm working on a database for maritime monitoring data. I made a classic EER-Model (MySQL Workbench), generated an interim database for Entity Framework 6 Code First by Database First to get started with Entity classes and DbContext implementation. From here on out I need to use EF Migrations
When I add the initial Migration the create table statements are naming the Tables like "DbContext"."TableName"**so the Database looks like **"SchemaName"."DbContext"."TableName" which is ugly AF.
I could write table names in modelbuilder fluentAPI or annotate them, but this is a hassle with a huge number of tables.
how can I alter the conventional naming? I just want the migrator to call the table like the property in DbContext derived class
You can also use the Table annotation:
[Table("InternalBlogs")]
public class Blog
See: Code First Data Annotations

Adding custom columns to ASP.NET Identity

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.

How to ignore a table/class in EF 4.3 migrations

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

Categories

Resources