Keep Database Content On Model Change - c#

Using the code-first approach available in the new 4.1 RC.
Is there any way to persist the current data stored in a database when the mode changes? The database is created by the entity framework, and usually the database is dropped and recreated on model changes.
Obviously as soon as the model is changed it will not be possible to use the context object to connect to the database to retrieve the data, so what are the options?

Code first doesn't support database migration / evolution yet. If you want to do incremental DB development use model first (EDMX) with DbContext Generator T4 template and Entity designer database generation pack which is able to create diff. scripts from the model.

From Scott Gu:
Importantly, though, the auto-create
database option is just an option – it
is definitely not required. If you
point your connection-string at an
existing database then EF “code first”
will not try and create one
automatically. The auto-recreate
option also won’t be enabled unless
you explicitly want EF to do this – so
you don’t need to worry about it
dropping and recreating your database
unless you’ve explicitly indicated you
want it to do so.

Related

EF Core DB first - Do I need the index definitions?

I am using EF Core (3.1 if that matters) with a DB first approach.
A while ago I generated the model using the Scaffold-DbContext command, and in the generated context file there are many index definitions, e.g.:
entity.HasIndex(e => new { e.ItemType, e.ItemID });
Since we had some index updates recently I was wondering - Do I actually need to update all the relevant index definitions in my model? Do I even need them at all? Do they have any influence on EF's performance or how the code runs, or can I just remove them and not worry about any updates made in the actual DB?
Thanks in advance
In the Database-First approach unlike Code-First, there is an existing database with its own configurations that may change in the future.
By this I mean, you always update your model based on the database objects and changes done in the database.
In your case, I suggest you use Database Project in visual studio for your database to make it under control by using Source Control. The following article might help you:
Create Your First Visual Studio Database Project
To my mind, it is not important to keep the database changes in the same application project. Keep all database objects in another database project and only use the database model for your application model. You can build it and then deploy the database project on SQL Server.
Indexes do not directly affect EF functionality, but the database performance affects its output. "An index is an on-disk structure associated with a table or view that speeds retrieval of rows from the table or view."
Clustered and nonclustered indexes described

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

How to update SQL Table structure from Entity Framework Model

I am new to Entity Framework. I have created an EF Model and successfully added some tables and relation. Then I Clicked Generate Database from Model and My DB has been updated. Then I renamed some columns and I don't know how to revert or apply the changes. And Update Model from database does not seems to work because the columns names are different yet.
I need to graphically sync DB with Model. I prefer the model data rather than db data.
Thanks in advance.
You might want to look into the Code-First approach of Entity Framework. Using that approach you'll define your model in your code, and when changing anything you can create a Migration which allows you to up- and down-grade the DB to a specific version from the package manager console (or just create the respective SQL scripts).
For more information on this subject please see this article on MSDN
Note that you can also reverse engineer the code first model from an existing database (see 3. Reverse Engineer Model in this MSDN article), and then enable migrations for that model (see Step 2: Enable Migrations in this MSDN article)
What I do when I make "updates" is do it on both sides manually, in db and then in model (by right click properties) if the change is small. If adding a "new" table I drag it over to model from db server connections panel.
The alternative I've seen others prefer to use in this cases is to stay away from Entity Framework and use Dapper where you pass queries to it and it handles the rest.
Dapper (Wins!) vs Entity Framework vs ADO.NET Performance Benchmarking

EF Initializer with multiple contexts for one database

I have an existing application with a SQL database that has been coded using a database first model (I create an EDMX file every time I have schema changes).
Some additional development (windows services which support the original application) has been done which uses EF POCO/DbContext as the data layer instead of an EF EDMX file. No initializer settings were ever configured in the DbContexts, but they never modified the database as the DbSet objects always matched the tables.
Now, I've written a seperate application that uses the existing database but only its own, new tables, which it creates itself using EFs initializer. I had thought this would be a great time to use EF Code First to handle managing these new tables. Everything worked fine the first time I ran the application, but now I am getting this error from some of my original EF POCO DbContexts (which never used an initializer).
The model backing the 'ServerContext' context has changed since the
database was created. Consider using Code First Migrations to update
the database
After some investigation, I've discovered that EF compares a hash of its schema with some stored hash in the sql server somewhere. This value doesn't exist until a context has actually used an initializer on the database (in my case, not until the most recent application added its tables).
Now, my other DbContexts throw an error as they read the now existing hash value and it doesn't match its own. The EF connection using the EDMX doesn't have any errors.
It seems that the solution would be to put this line in protected override void OnModelCreating(DbModelBuilder modelBuilder) in all the DbContexts experiencing the issue
Database.SetInitializer<NameOfThisContext>(null);
But what if later on I wanted to write another application and have it create its own tables again using EF Code first, now I will never be able to reconcile the hash between this theoretical even newer context and the one that is causing the issue right now.
Is there a way to clear the hash that EF stores in the database? Is EF smart enough to only alter tables that exist as a DbSet in the current context? Any insights appreciated.
Yes, Bounded DB contexts is actually good practice.
eg a base context class, to use common connection to DB, each sub class, uses the
Database.SetInitializer(null); as you suggest.
Then go ahead and have 1 large context that has the "view of the DB" and this context is responsible for all migrations and ONLY that context shoudl do that. A single source of truth.
Having multiple contexts responsible for the DB migration is a nightmare I dont think you will solve.
Messing with the system entries created by code first migrations can only end in tears.
Exactly the topic you describe I saw in A julie Lerman video.
Her suggested solution was a single "Migration" context and then use many Bounded DB contexts.
In case you have a pluralsight account:
http://pluralsight.com/training/players/PsodPlayer?author=julie-lerman&name=efarchitecture-m2-boundedcontext&mode=live&clip=11&course=efarchitecture
What EF version are you using? EF Code First used to store hash of the SSDL in the EdmMetadata table. Then in .NET Framework 4.3 thingh changed a little bit and the EdmMetadata table was replaced by __MigrationsHistory table (see this blog post for more details). But it appears to me that what you are really looking after is multi-tenant migrations where you can have multiple context using the same database. This feature has been introduced in EF6 - (currently Aplpha2 version is publicly available) Also, note that EdmMetadata/__MigrationHistory tables are specific to CodeFirst. If you are using the designer (Model First/Database First) no additional information is stored in the database and the EF model is not checked whether it matches the database. This can lead to hard to debug bugs and/or data corruption.

Can Entity Framework 4.1 designer "update model from database" for selected entities only?

The situation: Sometimes a database schema is not what you would consider an ideal representation of the system's information and you may not be able to change it. We have been using Entity Framework to create a nicer conceptual model to code against in situations like this. This means updating the model from the database and then changing it ourselves, either through the designer or through the .edmx file directly using a text editor.
The problem: When you update the model from the database, all your carefully made changes are thrown out the window. This can make adding new entities a real hassle as you are basically forced to do it through editing the .edmx file directly.
The question: Is there a way to get the Entity Framework to only update selected entities from from the database? Or is it possible to tell it to leave the rest of the model alone when adding a new entity?
Thanks!
No there is no way to make selective updates with built-in designer. Also the designer doesn't throw away all your changes. It usually doesn't touch conceptual model (except some rare occasions where it continuously renames some associations) and mapping but it always deletes storage model and override it with new definition. I worked without any problem with modifications to my conceptual model and mapping and running updates from the database.
Designer works as any other in Visual Studio - touching the generated code (storage model) is not supported feature. Once you do it you cannot use Update from database anymore.
There is commercial tool which probably supports better model updating - you can try a trial.
If by updating selected entities, you mean just one or more tables, you can delete those tables from the model, and then add them back in individually to pull in changes tables by choosing them individually - I do that often as underlying tables are changed (especially during development).
You do end up losing any manual changes you made to those re-added entities after the entity/table was pulled into the model (i.e. I often rename my navigation properties and then after each re-import of the table I need to manually rename them again).

Categories