So, I am diligently working with MVC 3... and ran into a very simple but convoluted problem. I was working with EF "code first" model and modified my model to add some validations...
Guess what ? It stopped running after that. Kept repeating the following message:
Guess what ? It stopped running after that. Kept repeating the following message:
The model backing the 'MyDBContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.
Solution:
We need to update the table in Sql Server to have the additional column you added to your entitiy class.
Database.SetInitializer(new DropCreateDatabaseIfModelChanges());
This line is used for in order to allow to edit database by making changes to Model objects.Add this line in Global.asax at Application_Start() method.
Inside the Application_Start method, define the Database initializer with one among the two options.
DropCreateDatabaseAlways: This will drop and recreate the database in every application start.
DropCreateDatabaseIfModelChanges: This will drop and create the database only if the underlined model changes.
Sample code:
protected void Application_Start()
{
Database.SetInitializer(newDropCreateDatabaseIfModelChanges());
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
Now it is working perfectly.
We need to update the table in Sql Server to have the additional column you added to your entitiy class.
Database.SetInitializer
This line is used for in order to allow to edit database by making changes to Model objects.Add this line in Global.asax at Application_Start() method.
Inside the Application_Start method, define the Database initializer with one among the two options.
DropCreateDatabaseAlways: This will drop and recreate the database in every application start.
DropCreateDatabaseIfModelChanges: This will drop and create the database only if the underlined model changes.
Sample code:
protected void Application_Start()
{
Database.SetInitializer
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
Now it is working perfectly.
Note: DropCreateDatabaseIfModelChanges should only be use early on in development, never on a production machine. If you pushed to a production machine and made schema changes, you'd loose all your data.
No comments:
Post a Comment