How to pre/populate database records with CodeFirst approach? - c#

I'm trying to write application using TDD and CodeFirst in ASP.NET MVC following 20486B training course guide, but I've stumbled upon a technical/methodology issue which I'll try to describe here. When I'll be coding my application I'd like to prepopulate the database which will be rebuilt each time I build/run/publish the app (as I am understanding CodeFirst). First that came to mind was to create a initial_data.sql script file with a bunch of inserts/updates on tables which will be fired up every build/run/publish of my app. It may work with small initial data set, but what when I would have to modify the application, which already would have a larger set of data in the database?
How can I "include" my initial_data.sql file each time Database is being rebuilt?
and second question
How I can CodeFirst on an existing database preserving records that are already in there?

Override the Seed() method in the Configuration class and load any data in there.
The Seed() method will be run every time the database is updated / migrations are run so make sure that it handles existing data gracefully without duplicate inserts etc.
In the Seed() method you have access to a DbContext() instance which you can use to execute SQL, but it also means you can use the ordinary EF API to update date. Specifically the AddOrUpdate() extension is great to use for loading initial data.

Related

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

Migrating Entity Framework without Migration Files

I am working on a project which is using Entity Framework code first for its data structure. It was created with code first, but was never migrated again and only has its initial migration data stored. Since then, the database has been modified directly through server explorer in VS2015.
There is no migration information about any changes and the database has critical information which I cannot lose.
Which brings me to my Questions.
If I create a new migration and update the database from it, will it wipe all changes which were not recorded in migrations and still leave the changes which were made as well?
The details of your question is a bit sketchy, but I will make some assumptions in order to help you along. Please correct where I am wrong.
I assume that you want to keep the data which resulted from the changes which were effected directly to the database, but you do not want to keep the changes that was effected to the database - in other words: keep the data but not the datastructures.
My advice is as follows
Always perform a full backup of your database when you are about to do something you are uncertain about.
If you can identify the tables you want to update, you can always use the SELECT INTO statement to create a quick backup of the specific tables only. These tables will not be removed when you do a EF database migration unless you explicitly script the deletion.
You can build the SELECT INTO statement into your EF migration via the Sql() method, or you can manually run the command against the database.
More information:
Click here to learn about EF code first migrations in general
Click here for a comprehensive code first migration reference
I believe following two posts will help you.
EF 4.3 Migration Walkthrough : http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-code-based-migrations-walkthrough.aspx
update:
Code First Migrations with an existing database
https://msdn.microsoft.com/en-us/data/dn579398.aspx

Bulk insert using code first migrations for azure

We have a lot of data that needs to be loaded into a number of tables. As far as I can see we have two options:
Include the data as part of the Configuration class seed method
Problems
1.a. this would be slow and involve writing a lot of C# code)
Use bulk insert with code first migrations - a lot quicker and probably a better solution.
Problems
2.a. It may prove tricky working with other data that gets loaded into the same tables as part of the seed.
2.b. It requires SQL Identity Insert to be switched on.
What solution is best and if it is 2 how do I go about bulk insert with code first migrations and how can I address the problems?
Bypassing EF and using ADO.NET/SQL is definitely a good approach for bulk data upload. The best approach depends on whether you want the data to be inserted as part of migration or just logic that runs on app start.
If you want it to be inserted as part of a migration (which may be nice since then you don't have to worry about defensive checks if the data exists etc.) then you can use the Sql(string) method to execute sql that uses whatever format and sql features you want (including switching IDENTITY_INSERT on/off). In EF6.1 there is also an overload that allows you to easily run a .sql file rather than having everything in code as a string.
If you want to do it on app start, then just create an instance of your context and then access Database.Connection to get the raw SqlConnection and use ADO.NET directly to insert the data.

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.

How do I seed specific values in a database every time the app runs?

I have an app that uses SSN's to look up people in a database. I am trying to force the 10 "ssn's" that I use for testing purposes to seed every time I run the app. I am currently dropping the table and reseeding the data with my false data but we are importing data from a real database to ours and I no longer want to do this.
Can someone lead me to a site or give me a hint on how I could go about this?
In Entity Framework you can customize a database initializer that won't drop the database (see near the end of this page). You could then put in the false data in the Initialize Database method so that it will run every time.
You have tagged this with Asp.net MVC3?
If this is a web-app, I'd consider using an Application_start event within Global.aspx

Categories