The model backing the 'DMSContext' context has changed - asp.net-mvc

I'm receiving the following error when running my mvc 4 app.
The model backing the 'DMSContext' context has changed since the database was created. Consider using Code First Migrations to update the database
I am running my app against an existing database and do no want to recreate the db each time the model changes.
I've found plenty of answers on google, but none have worked.
Specifically, I've tried adding the following to my global.asax:
Database.SetInitializer<DMSContext>(null);
and
Database.SetInitializer<DMSContext<Contact>>(null);
in the above, DMSContext is the DbContext. Contact is the Model where the change causing the error originates.
I've also tried adding the following to my context class:
public DMSContext() : base()
{
Configuration.AutoDetectChangesEnabled = false;
}
Most of the direction I've followed is from this page, but no luck.
The model backing the <Database> context has changed since the database was created

If you are working with Entity Framework Code First, its recommended that you enable migrations in your application. To do so, see this link.
Now every time you change something in your code (Mostly Entities), just build and then run Update-Database -Force in your Package Manager Console.
Let me know if you have any more questions.

Although you don't use migrations try to create one, do not run it, but you'll be able to see the differences with the database.

Check the name of the class, which inherits the DbContext. It's name have to be the same as the name of the connectionString in Web.config
<connectionStrings>
<add name="TheSameNameAsYourDbContextClass" providerName="" connectionString="" />
</connectionStrings>

Related

Unable to update database to match the current model because there are pending changes and automatic migration is disabled

I, for the life of me, can't get rid of this error message. I have tried almost everything that I can.
MyDBContext.cs
public MyDBContext() : base("ConnStr_Dev")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDBContext, DbMigrationsConfiguration<MyDBContext>>());
//Database.SetInitializer<MyDBContext>(null);
base.OnModelCreating(modelBuilder);
}
GenericRepository.cs
public void Insert(T obj)
{
table.Add(obj); //this is where it throws the error, inserting first time.
}
Tried all of these in different combinations
Enable-Migrations -EnableAutomaticMigrations -Force
Add-migration Initial -IgnoreChanges
Update-Database
I have tried deleting the Migrations table, deleting the entire database, everything.
Any Migrations experts please?
Edit: the DAL contains the GenericRepository and the context class.
I fought with this error too. I added the migration and then made what I thought was a trivial change.
This property: IMigrationMetadata.Target in your migration isn't random. It's computed based on the state of the model at the time the migration was completed. (That may be an oversimplification.)
So if you make additional changes, it looks as there are additional pending changes that require yet another migration.
In my case, because the changes hadn't been committed to source control, the fix was to delete and re-add the migration. It took a while to figure out the cause because the error message is unclear unless you already know what's causing it. But the lesson I learned (being relatively new to EF) is that changes to the models require either a new migration or re-doing the migration that I'm working on.
Delete your Migrations folder from your solution
Delete the dbo.__MigrationHistory table from your database
Open Package Manager Console and Enable-Migrations
Add your initial migration Add-Migration Initial
Update-Database
Done
You simply made changes to one or more of your entity classes. Whether you added a new property, changed the data type of that particular property or you simply added a new entity class, in all of those cases you indeed need to add a new migration.
Seeing that you've already tried that, make sure that when you execute the Add-Migration command in Package Manager Console that you've selected the project that contains your DBContext class, the Configuration class and Migrations folder. Furthermore, you are passing a specific connection string to the base class (DbContext) of the MyDBContext class. Make sure you are also upgrading and updating the correct database.
Know that you can perform an Add-Migration command and an Update command to a specific database:
Example snippets:
Add-Migration AddProperty1 -ConnectionString "Data Source=.\SQLEXPRESS;Initial Catalog=MyDatabaseCatablog;Connect Timeout=30;User ID=MyUser;Password=mypassword12345" -ConnectionProviderName "System.Data.SqlClient" -Verbose
and
Update-Database -ConnectionString "Data Source=.\SQLEXPRESS;Initial Catalog=MyDatabaseCatablog;Connect Timeout=30;User ID=MyUser;Password=mypassword12345" -ConnectionProviderName "System.Data.SqlClient" -Verbose
Hope this helps.
In my case the error was resolved by adding a DatabaseInitializerForType... appSetting.
<appSettings>
<add key="DatabaseInitializerForType EasyEntity.EasyContext, EasyEntity" value="EasyEntity.EasyInitializer, EasyEntity" />
This error is weird enough in my case, I forgot to uncomment the CONNECTIONSTRING setting, means having a proper connectionstring resolved this error. Hope it helps!

The model backing the 'AccountingDBContext' context has changed since the database was created. Consider using Code First

I know there are many topics about this error message but none of them is similar my problem. I am using Entity Framework 6. I have changed my entity and I have to run add-migration and then update-database. but when I run add-migration the newly created class public partial class Test: DbMigration contains two empty Up and Down methods. so when I run update-database it does not make any changes on the database. and I am get this error always.
I am getting this error when I run update-database. I think the problem occur becasue UP and Down methods are empty and no changes are made into the database when I run update-database.
in Application_Start() Method in Global.asax.cs file write as first line this
Database.SetInitializer<YourDBContext>(null);
For those that want to know what was the problem.
When you create a MVC 5 project with Idenity, it adds ApplicationDbContext class to connect to the database. I had created another DBContext for my entities. When I changed my entities and run add-migration it affected only chnages that was made for those ootb entities which belong to ApplicationDbContext not my DBContext. and When I run update-database it does not update my entities. I added all my entities to ApplicationDbContext and run add-migration then update-database and it solved the problem.

How to update-database Programmatically in EntityFramework Codefirst?

i am writing a simple CMS over ASP.NET MVC framework (for college final project).my problem is with module's data-migration strategy.as each module will update the database schema when it is installed , a database migration mechanism must be implemented in module installation system.ok , data-migration in entity framework is already there (thanks to MS) , but the migration commands run in package manager console.is there any way to run a Data-Migration code Programmatically?
any help is very appreciated.
If you've enabled the automatic migrations in Package Manager Console you can use the following code in an init section of your app (e.g. in SimpleMembershipInitializer):
var migratorConfig = new Migrations.Configuration();
var dbMigrator = new DbMigrator(migratorConfig);
dbMigrator.Update();
Where Migrations.Configuration is the migration configuration class placed in your project into your namespace (YourProjectNamespace.Migrations).
If you use it programmatically you should at first turn off the EF initializer:
Database.SetInitializer<YourDBContext>(null);
The thing is the programmatic update creates a database if it doesn't exist.
This class exposes the EF migrations in code:
System.Data.Entity.MigrateDatabaseToLatestVersion
In EF, migrations work on a whole database though - not modular parts of one.
Just found this class too:
System.Data.Entity.Migrations.DbMigrator

EF 4.3 Auto-Migrations with multiple DbContexts in one database

I'm trying to use EF 4.3 migrations with multiple code-first DbContexts. My application is separated into several plugins, which possibly have their own DbContext regarding their domain. The application should use one single sql-database.
When I try to auto migrate the contexts in an empty database, this is only successful for the first context. Every other context needs the AutomaticMigrationDataLossAllowed-Property set to true but then tries to drop the tables of the previous one.
So my question is:
How can I tell the migration-configuration just to look after the tables defined in their corresponding context and leave all others alone?
What is the right workflow to deal with multiple DbContexts with auto-migration in a single database?
Thank you!
Here is what you can do. very simple.
You can create Configration Class for each of your context.
e.g
internal sealed class Configuration1 : DbMigrationsConfiguration<Context1>{
public Configuration1 (){
AutomaticMigrationsEnabled = false;
MigrationsNamespace = "YourProject.Models.ContextNamespace1";
}
}
internal sealed class Configuration2 : DbMigrationsConfiguration<Context2>{
public Configuration2 (){
AutomaticMigrationsEnabled = false;
MigrationsNamespace = "YourProject.Models.ContextNamespace2";
}
}
Now you add migration. You dont need to enable migration since you already did with the 2 classed above.
Add-Migration -configuration Configuration1 Context1Init
This will create migration script for context1. your can repeat this again for other Contexts.
Add-Migration -configuration Configuration2 Context2Init
To Update your database
Update-Database -configuration Configuration1
Update-Database -configuration Configuration2
This can be done in any order. Except you need to make sure each configration is called in sequence.
Code First Migrations assumes that there is only one migrations configuration per database (and one context per configuration).
I can think of two possible solutions:
Create an aggregate context that includes all the entities of each context and reference this "super" context from your migrations configuration class. This way all the tables will be created in the user's database, but data will only be in the ones that they've installed plugins for.
Use separate databases for each context. If you have shared entities between the contexts, add a custom migration and replace the CreateTable(...) call with a Sql("CREATE VIEW ...") call to get the data from the entity's "originating" database.
I would try #1 since it keeps everything in a single database. You could create a seperate project in your solution to contain your migrations and this "super" context. Just add the project, reference all of your plugins' projects, create a context that includes all of the entities, then call Enable-Migrations on this new project. Things should work as expected after that.
I have a working site with multiple contexts using migrations. However, you do need to use a separate database per context, and it's all driven off of a *Configuration class in the Migrations namespace of your project, so for example CompanyDbContext points to Company.sdf using CompanyConfiguration. update-database -configurationtypename CompanyConfiguration. Another LogDbContext points to Log.sdf using LogConfiguration, etc.
Given this works, have you tried creating 2 contexts pointing at the same database and telling the modelbuilder to ignore the other context's list of tables?
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Ignore<OtherContextsClass>();
// more of these
}
Since the migrations work with the ModelBuilder, this might do the job.
The crappy alternative is to avoid using Automatic Migrations, generate a migration each time and then manually sift through and remove unwanted statements, then run them, although there's nothing stopping you from creating a simple tool that looks at the Contexts and generated statements and does the migration fixups for you.
Ok, I have been struggling with this for a day now, and here is solution for those seeking the answer...
I am assuming that most people reading this post are here because they have a large DbContext class with a lot of DbSet<> properties and it takes a long time to load. You probably thought to yourself, gee, that makes sense, I should split up the context, since I won't be using all of the dbsets at once, and I will only load a "Partial" context based on the situation where I need it. So you split them up, only to find out that Code First migrations don't support your way of revolutionary thinking.
So your first step must have been splitting up the contexts, then you added the MigrationConfiguration class for each of the new contexts, you added the connection strings named exactly the same as your new Context classes.
Then you tried running the newly split up contexts one by one, by doing Add-Migration Context1 then doing Update-Database -Verbose...
Everything seemed to work fine, but then you notice that every subsequent Migration deleted all tables from the Previous migration, and only left the tables in from the very last migration.
This is because, the current Migrations model expects Single DbContext per Database, and it has to be a mirror match.
What I also tried, and someone suggested here doing that, is create a single SuperContext, which has All the Db sets in it. Create a single Migration Configuration class and run that in. Leave your partial Context classes in place, and try to Instantiate and use them. The EF complains that the Backing model has changed. Again, this is because the EF compares your partial dbcontext to the All-Sets context signature that was left over from your Super Context migration.
This is a major flaw in my opinion.
In my case, I decided that PERFORMANCE is more important than migrations. So, what I ended up doing, is after I ran in the Super context and had all the tables in place, I went into the database and Manually deleted _MigrationHistory table.
Now, I can instantiate and use my Partial Contexts without EF complaining about it. It doesn't find the MigrationHistory table and just moves on, allowing me to have a "Partial" view of the database.
The trade off of course is that any changes to the model will have to be manually propagated to the database, so be careful.
It worked for me though.
As mentioned above by Brice, the most practical solution is to have 1 super DbContext per application/database.
Having to use only 1 DbContext for an entire application seems to be a crucial technical and methodological disadvantage, cause it affects Modularity among other things. Also, if you are using WCF Data Services, you can only use 1 DataService per application since a DataService can map to only 1 DbContext. So this alters the architecture considerably.
On the plus side, a minor advantage is that all database-related migration code is centralized.
I just came across this problem and realised the reason I had split them into different contexts was purely to have grouping of related models in manageable chunks and not for any other technical reason. Instead I have declared my context as a partial class and now different code files with different models in them can add DbSets to the DbContext.
This way the automigration magic still works.
I've got it working with manual migrations, but you can't downgrade as it can't discrimitate between configurations in the __MigrationHistory table. If I try and downgrade then it treats the migrations from the other configurations as automatic and since I don't allow data loss it fails. We will only ever be using it to upgrade though so it works for our purposes.
It does seem like quite a bit ommision though, I'm sure it wouldn't be hard to support it provided there was no overlap between DbContexts.
Surely the solution should be a modification by the EntityFramework team to change the API to support the direct modification of the _MigrationHistory table to a table name of your choice like _MigrationHistory_Context1 such that it can handle the modification of independent DbContext entities. That way they're all treated separately, and its up to the developer to ensure that the names of entities don't collide.
Seems like there are a lot of people who share my opinion that a duplicate DbContext with references to the superset of entities is a bogus non-enterprise friendly way to go about things. Duplicate DbContexts fail miserably for modular (Prism or similar) based solutions.
I want people to know that the answer with this below is what worked for me but with one caveat: don't use the MigrationsNamespace line.
internal sealed class Configuration1 : DbMigrationsConfiguration<Context1>{
public Configuration1 (){
AutomaticMigrationsEnabled = false;
MigrationsNamespace = "YourProject.Models.ContextNamespace1";
}
}
internal sealed class Configuration2 : DbMigrationsConfiguration<Context2>{
public Configuration2 (){
AutomaticMigrationsEnabled = false;
MigrationsNamespace = "YourProject.Models.ContextNamespace2";
}
}
However, I already had the 2 databases established with their own contexts defined so I found myself getting an error saying "YourProject.Models namespace already has ContextNamespace1 defined". This was because the "MigrationsNamespace = "YourProject.Models.ContextNamespace2";" was causing the dbcontext to be defined under the YourProjects.Models namespace twice after I tried the Init (once in the migration Context1Init file and once where I had it defined before).
So, I found that what I had to do at that point was start my database and migrations from scratch (thankfully I did not have data I needed to keep) via following the directions here:
http://pawel.sawicz.eu/entity-framework-reseting-migrations/
Then I changed the code to NOT include the MigrationsNamespace line.
internal sealed class Configuration1 : DbMigrationsConfiguration<Context1>{
public Configuration1 (){
AutomaticMigrationsEnabled = false;
}
}
internal sealed class Configuration2 : DbMigrationsConfiguration<Context2>{
public Configuration2 (){
AutomaticMigrationsEnabled = false;
}
}
Then I ran the Add-Migration -configuration Configuration1 Context1Init command again and the Update-Database -configuration Configuration1 line again (for my 2nd context too), and finally, everything seems to be working great now.

Entity Framework 4 and DB2: database generation error

We are using Entity Framework 4 RC on Visual Studio 2010 with DB2 version 9.7.3.4. I also have the VS Add-ins and can see the DB2 database in Server Explorer. I have created a very simple VS console project and it works fine against SQL Server, so I know it is valid. I have references to "IBM.Data.DB2.9.7.3" and "IBM.Data.DB2.Entity" in my project.
In app.config my connnection string is:
<add name="ProductContext"
providerName="IBM.Data.DB2"
connectionString="Database=DB2TEST;User ID=XXXX;PWD=XXXX;Server=XXXX;Persist Security Info=True;"/>
The first statement in my code is a database initializer:
DbDatabase.SetInitializer<ProductContext>(new DropCreateDatabaseIfModelChanges<ProductContext>());
During run-time when I reach a line that causes a change to the data context I get the error:
Model compatibility cannot be checked
because the database does not contain
model metadata.
Since I requested that the database be dropped, this does not seem to be a logical error. Does anyone know what the cause could be?
I would try to inherit from CreateDatabaseIfNotExists first, which will add the EdmMetadata table to the schema. I believe the error is that EF is saying that it cannot find that table.
So
DbDatabase.SetInitializer<ProductContext>(new CreateDatabaseIfNotExists<ProductContext>());
Run it once, then change to DropCreateDatabaseIfModelChanges once the EdmMetadata table exists.
Try removing the IncludeMetadataConvention like this:modelBuilder.Conventions.Remove<System.Data.Entity.Infrastructure.IncludeMetadataConvention>();
To avoid the "dbo" issue, just map all your entities using either DataAnnotation attributes or Fluent mapping:
[Table("Product", SchemaName = "MySchema")]
public class Category { //DataAnnotoaion approach
modelBuilder.Entity<Category>().ToTable("Categories", "MySchema"); //Fluent approach

Resources