I have a webAPI hosted in Azure as my back-end. I am using Code-First to create my entities. I can pre-feed my DB fine via the seed method, but if I am done with my model changes and then remember that I need to add something to the seed, there is no way to run the seed method.
Multiple posts suggest the simple run update-database. I do see: "Running Seed method." and then publish to azure, my table is still empty. And I don't want to change the models just to trigger the seed, because that is just not clean solution.
I have already tried using each of the commented lines but no avail
public MyContext() : base("name=MyContext")
{
//Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, MyProject.Migrations.Configuration>("DefaultConnection"));
//Database.SetInitializer<MyContext>(new DropCreateDatabaseAlways<MyContext>());
}
is there something I should be doing at the azure side or it just plainly doesn't work unless I change one my models!?
Update1:
I already the migrations folder and follow the commands to enable it and update the db and when I have a model change, the db updates just fine. That works, no issue there. The only issue if I want to add things to the seed method and I want to execute it without having to change my model.
If you are using code first then you can manage and handle all your migrations easily.
you need to type "enable-migrations" using package manger console.After this you will have a folder named Migrations.
Check this link for additional information.
Let know if you have any issues.
Related
I have a solution where I do not have one default database. I have a master Database that are returning a connection string for the customer that is requesting data, and each customer has their own database. I am using migration (and has AutomaticMigrationsEnabled set to false) and code first.
The command “update-database” is “excecuted” from the code (Database.SetInitializer(new MigrateDatabaseToLatestVersion());).
The first time is it all working fine, but when I afterwards will add a migration, I cannot, because there are pending migrations. I can not run update-database from VS because the connections string is set on runtime.
What is the right way to handle a setup like mine, with migrations and Entity Framework 6?
Thanks very much in advance
What you have is so called multitenant application. And yes, EF migrations can support such scenario, too.
You just have to change your migrator from the MigrateDatabaseToLatestVersion to a custom one that migrates the exact database the context is created for.
Then, forget about executing update-database from a powershell console. This always updates the default database! Instead, your custom migrator will automatically update the database you connect to.
Complete source code of the custom migrator can be found in my blog entry:
http://www.wiktorzychla.com/2013/05/entity-framework-5-code-first-multi.html
Be aware that due to a bug in eariler versions of EF, migrations in a multitenant scenario work correctly starting from EF 6.1.3.
Because of this bug, your multitenant application could incorrectly assign connection strings to newly created db contexts.
https://entityframework.codeplex.com/SourceControl/changeset/4187b1c308316a22b38ef533b1409024bc0f7406
Add-Migration and Update-Database from the console still refer to a database.
To create a DbContext, these commands either use its parameterless constructor (if you have one), or it instantiates an IDbContextFactory<T> if one exists and calls its Create method to get one.
The fact you don't use this specific database at run-time isn't really important, but you do need one somewhere at design time to allow you to add migrations.
I have an application using a EF model for the database. This application is going to run on multiple computers in the same network using one database. To make sure this works ok when there are updates. I want to control the migration and installation of the database.
I thought I could disable the EF initializer and in my application startup checks using context.database.Exists() and context.database.CompatibleWithModel if the application matches the database. If this is not the case I want to create it after I check if all client are offline.
But my problem is when I run context.database.create() ,
I get an error
{"Unable to update database to match the current model because there
are pending changes and automatic migration is disabled. Either write
the pending model changes to a code-based migration or enable
automatic migration. Set
DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable
automatic migration."}
What is the best approach to controlling the creation of the DB and migrates from code? And not from the initializer.
The problem you've got seems not related to db creation. Your model just simply does not comply any more with what migrations states. Just run add-migration script to regenerate migration files and everything should work fine. If you would like to allow automatic migrations (not required to regenerate migration classes after model changes - but generaly this is a bad idea) just set AutomaticMigrationsEnabled = true in Configuration class for migrations and this will as well fix your error. To control migrations from code the best thing you could use is DbMigrator. You use it like that:
var migrator = new DbMigrator(new MyMigrationsConfiguration());
migrator.Update();
With the Update method you can define to which migration you want to migrate your db.
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.
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.
All right, I'm using EntityFramework migrations, and they work fine, but when I run my application, (Web API) and the first time the context is used, the schema is created automatically for me. I DO NOT want that. I'd like to see an exception specifying that the tables do not exist or something like that.
In my configuration class I have something like this:
this.AutomaticMigrationsEnabled = false;
I thought that was going to be enough but EntityFramework keeps re-creating my database schema.
Since I'm using a Continuous Integration and Continuous Delivery process I want to use EF migrations to create the scripts for me and just check in my scripts and the scripts will be executed against the database for me (I already created that process)
So how can stop EntityFramework migrations for trying to create my database schema automatically when the application runs (when the context is accessed the first time in the AppDomain)?
Unset the database initializer for your context.
Database.SetInitializer<MyContext>(null);