I have used MVCScaffolding from Nuget Package Manager and followed the brief tutorial on how it works.
It seems simple enough,and when I run
Scaffold Controller Team –Repository -Force
it will create all the repository pattern stuff surrounding "Team".
However, in an attempt(and success) to break this, I decided to add in an additional field to the "Team" class (myRandomField
).
As I expected, when I compiled I got an error in the MVC View which was:
The model backing the 'MvcApplication1Context' 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.
Obviously this error is because I have updated the model (Code-first??) and the DB is now 'out of sync' with my model.
What is the best approach to get around this issue? Is there an easy way to have to DB sync with the model - I plan on doing a lot of editing to my models as the project I am starting will be rolled out gradually (So doing a complete database rebuild each time is out the question) Is code first the right approach for me in this case? I really like this plugin/tool would be a shame not to use it.
jad,
as mentioned in my comment above, if you're 'happy' to lose all exisiting data in your DB, then you can add the following into your global.asax:
[Conditional("DEBUG")]
private static void InitializeDb()
{
using (var db = new YourContext())
{
// double indemnity to ensure just sqlserver express
if (db.Database.Connection.DataSource != null
&& db.Database.Connection.DataSource.IndexOf("sqlexpress",
StringComparison.InvariantCultureIgnoreCase) > -1)
{
// Initializer code here
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<YourContext>());
}
}
}
and then call this from Application_Start()
, i.e.
protected void Application_Start()
{
InitializeDb();
ViewEngines.Engines.Add(new MobileViewEngine());
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
if you wish to retain the data, then you'll have to use a data migration tool. I used the Red Gate tools (SQL Comparison Bundle) to perfom this. Basically, this look at your new schema and your old schema and migrates existing data over into the new schema, ready for test and deployment, all without touching the original db file.
I think this should work well for you.