Web config Change User Ef Tries to Create Db Again
Tips When Making Changes in Entity Framework Code First Models after Scaffolding
When you lot scaffold an existing Entity Framework model, using MVC5 scaffolding in Visual Studio 2013, yous can easily run into the issue of "The model backing the <DbContextName> context has changed since the database was created" as shown below.
For example, in an MVC project, add the following model.
public class Production { public int Id { get; set up; } public string Name { become; set; } }
Scaffold the Product model using "MVC 5 Controller with views, using Entity Framework" scaffolder in Visual Studio 2013. View the generated pages, Index/Edit/Details/Create, to verify things are working properly.
At present, suppose we demand to modify the Product model to add more fields, similar Clarification and Category.
public class Product { public int Id { get; set; } public cord Name { get; gear up; } public string Description { get; set; } public string Category { get; set; } }
Scaffold the Product model once more and view a scaffold page, you will encounter the error bulletin mentioned above. The exception is caused by the model alter, non actually a scaffolding effect. All the same, because of the club in which users practice things, it might sometimes appear to be related to scaffolding.
There are a few ways to workaround this error; each has some pros and cons, depending on what y'all need.
i) Code Kickoff Migration with Entity Framework.
Following the instructions at Lawmaking First Migration requires a number of steps.
First, you need to bring up "Parcel Manager Console", Tools –> Library Package Manger –> Package Managing director Panel, and run the Enable-Migrations command in the console as the first step to enable migrations for your context.
PM> Enable-Migrations -ContextTypeName WebApplication7.Models.WebApplication7Context
Checking if the context targets an existing database...
Detected database created with a database initializer. Scaffolded migration '201309271941079_InitialCreate' corresponding to existing database. To use an automatic migration instead, delete the Migrations folder and re-run Enable-Migrations specifying the -EnableAutomaticMigrations parameter.
Code Commencement Migrations enabled for projection WebApplication7.
From now on, each time you change the model and re-run the scaffolding, you need to run the Add-Migration, and Update-Database commands. In our example above, after calculation Description and Category, we run those commands as follows.
PM> Add-Migration AddDescriptionCategory
Scaffolding migration 'AddDescriptionCategory'.
The Designer Lawmaking for this migration file includes a snapshot of your current Lawmaking First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If yous make additional changes to your model that you desire to include in this migration, then you tin re-scaffold information technology past running 'Add-Migration AddDescriptionCategory' once more.
PM> Update-Database
Specify the '-Verbose' flag to view the SQL statements beingness practical to the target database.
Applying explicit migrations: [201309280107120_AddDescriptionCategory].
Applying explicit migration: 201309280107120_AddDescriptionCategory.
Running Seed method.
PM>
Now you can test view the scaffolded pages and won't encounter the error anymore.
The good thing about this approach is you just modify the exact table representing the model that you're changing, and go out the rest of the database intact. Notwithstanding, if you do a lot of changes on the model and want some quick verification of the scaffold pages, going through those steps each time tin add a considerable amount of fourth dimension. As well, those steps will add a number of files into your projects that can grow quickly.
Migration is commonly the best choice when you apply it to deploy to product the initial time and when y'all're deploying updates to production afterwards. For more than information nigh migrations for deployment, see http://www.asp.net/web-forms/tutorials/deployment/visual-studio-web-deployment/introduction.
For rapid development, selection ii and 3 beneath might be a meliorate pick.
2) Modify the Database name in the connectionString
A quick workaround to the existing database effect without going through all the database migration steps would be to modify the connection string in web.config. Each fourth dimension you change the lawmaking start model and scaffold it, you tin requite the connexion string a new "Initial Catalog" and "AttachDbFilename" value.
This approach volition create a new database each time you give a new database name in the connection string and exit the erstwhile database unused. This might not exist ideal if you already have a large existing database. Withal, it could exist useful if you but want to verify something quick one time or twice.
3) Database Initializer with Entity Framework
With the second workaround, you still need to remember to modify the connection cord each time the model is changed. If you want to make one setting, and forget nigh information technology when you're building your app, y'all can achieve this with a custom initializer class. EF will drib, recreate and re-seed the database each time the model changes, and you prepare upwards this action only once in your projection.
Following is an example of a custom initializer class.
public class SchoolInitializer : DropCreateDatabaseIfModelChanges<SchoolContext>
{
protected override void Seed(WebApplication3Context context)
{
var students = new List<Student>
{
new Educatee { FirstMidName = "Carson", LastName = "Alexander", EnrollmentDate = DateTime.Parse("2005-09-01") },
new Educatee { FirstMidName = "Meredith", LastName = "Alonso", EnrollmentDate = DateTime.Parse("2002-09-01") },
new Student { FirstMidName = "Arturo", LastName = "Anand", EnrollmentDate = DateTime.Parse("2003-09-01") },
new Educatee { FirstMidName = "Gytis", LastName = "Barzdukas", EnrollmentDate = DateTime.Parse("2002-09-01") },
new Educatee { FirstMidName = "Yan", LastName = "Li", EnrollmentDate = DateTime.Parse("2002-09-01") },
new Educatee { FirstMidName = "Peggy", LastName = "Justice", EnrollmentDate = DateTime.Parse("2001-09-01") },
new Student { FirstMidName = "Laura", LastName = "Norman", EnrollmentDate = DateTime.Parse("2003-09-01") },
new Student { FirstMidName = "Nino", LastName = "Olivetto", EnrollmentDate = DateTime.Parse("2005-09-01") }
};
students.ForEach(due south => context.Students.Add(s));
context.SaveChanges();
}
}
Then add the following code in Global.asax.cs
public class MvcApplication : System.Spider web.HttpApplication { protected void Application_Start() { Database.SetInitializer<SchoolContext>(new SchoolInitializer()); } }
From now on, you tin just focus on building the right model for your awarding, scaffold, and exam it equally many times as yous need, and don't have to practice anything actress in order to avoid the fault mentioned at the beginning of this web log.
This approach will drop and create a new database merely when the model is inverse, and it won't exit backside a lot of unused databases, which option ii will do.
Another way to tell Entity Framework to use your initializer grade is to add together an element to the entityFramework element in the awarding'southward Web.config file, instead of modifying the Global.asax.cs file. For more information virtually how to do it, you can read Tom'southward fabulous blog at Creating an Entity Framework Information Model for an ASP.NET MVC Awarding. Setting up the initializer in the Web.Config file is sometimes preferable because you tin can plough it on or off or change it without changing code.
Source: https://devblogs.microsoft.com/dotnet/tips-when-making-changes-in-entity-framework-code-first-models-after-scaffolding/
Post a Comment for "Web config Change User Ef Tries to Create Db Again"