Everything was working just fine
This error occurred to me when I made changes to my Model and did not make migration for the changes to update the database.
If you have ever made changes to your model in Code First Migration Schema
Don't forget to add migration
add-migration UpdatesToModelProperites
The above command will read all the changes you have made in the model and will write it in the Up() and Down() methods.
Then simply update your database using the below command.
update-database
This what worked for me.
I spent many days to solve this issue, analyzed many different posts and tried many options and finally fixed. This 2 projects in my solution using EF code first migrations:
I got this error when requested WebApi...
My environment:
Here I collected all the remarks you should pay attention and all conditions/requirements which must be met, to avoid mentioned exception :
Name of connection string e.g. MyConnectionString in config file of startup project (Web.config/App.config):
<configuration>
<connectionStrings>
<add name="MyConnectionString" connectionString="...">
</connectionStrings>
<configuration>
should be equal to parameter passed in constructor of your DbContext:
public partial class MyDbContext : DbContext
{
public MyDbContext()
: base("name=MyConnectionString"){}
...
And the main, which fixed my issue: It is weird, but in my WebApi/bin folder DataModel.exe was old, not refreshed since last build. Since migrations was embedded in my assembly DataModel.exe then my WebApi updated database using old mirgations. I was confused why after updating database in WebApi it not corresponds to latest migration script from DataModel. Following code automatically creates(if not exists) or updates to latest migration local database in my WebApi/App_Data folder.
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<ODS_DbContext, Configuration>());
...
I tried clean and rebuild solution but it did not help, than I completely removed bin and obj folders from WebApi, deleted database files from WebApi/App_Data, built, restarted WebApi, made request to it, it created correct database - lazy initialization (using lines above), which corresponds to latest migration and exception didn't appear more. So, this may fix your problem:
This can happen when you change the data annotation of a model property. for example: adding [Required] to a property will cause a pending change in the database design.
The safest solution is to run on the Package Manager Console:
add-migration myMirgrationName
which will display the exact changes in the Up() method. Therefore, you can decide if you really want to apply such changes via the:
update-database
Otherwise, you may just delete the latest migration from the __MigrationHistory table and from the Migrations folder the Solution Explorer.