Entity Framework on a SQL instance - asp.net-mvc

Every EF tutorial I've looked at requires LocalDB or SQL Express to be used in a code-first approach with EF.
Is there a way to connect to a traditional SQL DB (2014) instance using code-first EF and have EF create the schema in the DB? Or would I have to connect to a DB with an exsiting matching schema when switching to production?
It's fine to use LocalDB for dev purposes, but when deploying to production, I'd like to plug into an actual and existing SQL DB. Is there a way to do this without plugging into a DB that has had its schema manually made to match the EF models?

I would try using Entity Framework's Code First Migrations (http://msdn.microsoft.com/en-us/data/jj591621.aspx).
Short version:
1) In your DbContext, set the initializer to CreateDatabaseIfNotExists similar to Database.SetInitializer<YourDbContext>(new CreateDatabaseIfNotExists<YourDbContext>());
This will allow EF to create the DB if no database exists (the first time the application is run).
2) Next, go to the Package Manager Console, select your Database project (if separate), and enter the command Enable-Migrations. This will create some migration scaffolding and an initial migration.
Whenever you change your database model in code from then on, do the following steps:
3) After you've changed your code-first model, go to the Package Manager Console, select the Database project, and type the command Add-Migration MigrationNameHere This will scaffold out a new separate migration that can be applied to your database. Note, this command will run for whatever db is in your current connection string config.
4) To apply the migration, and update your database to the new schema, type the command Update-Database. If everything goes well, your database will be updated (with data) to the new schema! You should now be able to run your MVC project without db errors.
Keep in mind, this is the very basic version of db-migrations, please try it out on a dummy project first, and of course backup your data. If the changes are complex, or you need to do a special migration of data, you can edit the scaffolded migration code in the Migrations folder created, before doing the Update-Database.
Hope this helps!

Related

EF6 Updating Code First Model from the Database

I inherited an ASP.NET MVC application using Entity Framework 6.2. The application was originally built using Code First and I can see migrations that have been applied to the database. The structure of the database seems accurate.
However, a ton of relationships have been added to fix referential integrity issues and these were done directly on the database. There are a bunch of them. Can someone help me to update the models from the database in a code first implementation? Ideally it would remain code first, not a conversion, but I need to do a one time update.
I'm more familiar with newer EF Core and I thought it would as easy as running a scaffold-dbcontext command with a -force and some cleanup. But no such luck in this older version. Is there something similar?
Depending on what a 'ton' means and whether you need to keep the old migrations you could either just rebuild the entire model by doing code first from existing database or you could save the generated code into a folder and do a manual reconstruction:
Run code first from existing database into a new folder.
Map new fields and navigation properties into existing models.
Fix up any fluent code (modelBuilder).
Generate a migration which should include those changes.
A good test would be restoring a pre-change version of the database and running the migration against it. Then perhaps use a schema compare utility.
Apply the migration to databases. If the database already includes the changes, comment out the Up() code before applying. This will update the stored model so the next migration does not repeat these changes.

Entity Framework 6 Migrations: How to disable automatic Update-Database on Database initialize?

We have a project running EF6 and have now activated Migrations. The problem we have is that we ha a lot of Data that needs to be added to the database when it is created. This worked well until we needed to add data in the migration part so it is part becomes part of the SQL script. Because when we try and create a new database on our development machines the migration steps are done before the Initializer's seed method and some of the data in the migration step depends on that seed data.
Is there some way to just get the initial database, without any migrations, plus the Initializer's seed data? Or do we need to move the critical data to the InitialCreate mirgations Up method?
The production database will cannot be wiped at this stage and thus we need to add all new production data to the migration step.
Edit: In the end we just moved the effected data to the Up method in migrations, not the way I wanted to do it but we where short on time and this solved the problem.
Migrations also have a Seed method you can override that takes place after the Up() method. You can use the AddOrUpdate command in case data may exist. http://www.asp.net/web-api/overview/data/using-web-api-with-entity-framework/part-3

How do I generate the migration to create the initial tables?

I want to be able to generate my table structure entirely using migrations.
Thus the first migration should create the tables.
I thought I could achieve this by dropping the database and deleting all the migrations as well as the Configuration.
However after I enable the migrations using
enable-migrations
and create my first migration using
Add-Migration One
the up method in the migration is empty.
In the configuration I have
AutomaticMigrationsEnabled = false;
In the Context Creation I have
Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, Configuration>());
If I run the application a blank database is created
I am using EF Code First 5 on Windows 7 with C# WInforms
I got it working using
Add-Migration InitialCreate
The initial time I tried this it didn't work. I arent sure why

How does ASP MVC 4 know which db migration you're on?

I have been developing my app in a code-first approach atop an exisiting database.
Only now do I have a need to run a migration. I don't want to destroy this database when my model changes because it is very large and it has nice sample data in it.
How can I run a migration without the framework telling me that there are pending changes to apply? (The code runs anyway as I do my migrations from Rails-tho I would like to do them from here)
I do not want to set up automatic migrations because I am working on a big database with lots of seeded data that I do not want to delete/recreate. I also want to have control over what is made, deleteded and when.
This is also needed for when I take it to production, I'd like to roll out the changes via Migration instead of manually. How can I migrate by adding in/removing the fields I want and not have EF care about what it is I do?
If I know how it knows which one it is on (like Rails) can I trick her into thinking that she can run the migrations I want?
I thought that setting the initializer by:
Database.SetInitializer<MyDbContext>(new CreateDatabaseIfNotExists<MyDbContext>
would take acre of it, but it does not.
To answer the question in the title, because there's a sys table __MigrationHistory which tells EF that there is a difference in your tables vs what the database has.
As far as how to do it (from package manager console):
Enable-Migrations
In the configuration class set AutomaticMigrations = false;
Set your Database.SetInitializer<Context>(null) so it doesn't DropCreate or Update
AddMigration <name> to queue any pending changes to a change model
Update-Database will call the MigrationName.Up method to alter the database with any changes (sans losing data).
There's a Table "__MigrationHistory" that EF uses to store Migration Name / Order. You can backup this table in your dev environment, then delete these records. When you deploy to production, you run the migrations. Another option is use Database compare (dev / prod) and get scripts to change your tables / data.

Getting Initial Entity Framework Migrations Script

I just installed Entity Framework Migrations, added a property to a class, and gave EF Migrations a whirl.
My development database was promptly updated. So far, so good.
Now, I want to create a change script for this initial use of Migrations for the production database. Note there was a pre-existing database because I applied this to an existing project.
The migrations I have are:
PM> Get-Migrations
Retrieving migrations that have been applied to the target database.
201204102238194_AutomaticMigration
201203310233324_InitialCreate
PM>
I thought I could get a delta script using the following:
Update-Database -SourceMigration:201203310233324_InitialCreate -TargetMigration:201204102238194_AutomaticMigration -script
However, that gives me the error:
'201204102238194_AutomaticMigration' is not a valid migration.
Explicit migrations must be used for both source and target when
scripting the upgrade between them.
Just to see what would happen, I reversed the two parameters (backward migration) and did get the script I would expect after adding the -force flag (new columns dropped).
How can I get a script for this first migration?
The right way to start using EF migrations with an existing database is to start with adding an empty migration that contains the metadata of the current database.
I think that you have to roll back to a model that is compatible with the initial database schema. Then run the following command:
add-migration InitialSchema -IgnoreChanges
That should give you an initial migration, that does nothing, but contains the metadata of the current model. You can of course add migrations later with -IgnoreChanges if you've expanded your code model to cover more of the tables already present in the database.
Once you have that initial migration step in place, the scripting would work.
Generally I would not recommend to use automatic migrations unless you only ever intend to only use automatic migrations. If you want some kind of control over the changes to the database (including scripting them) then code-based migrations is the way.

Resources