The error message :
"The model backing the 'AddressBook' 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 RecreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data."
I am trying to use the code-first feature and following is what I wrote:
var modelBuilder = new ModelBuilder();
var model = modelBuilder.CreateModel();
using (AddressBook context = new AddressBook(model))
{
var contact = new Contact
{
ContactID = 10000,
FirstName = "Brian",
LastName = "Lara",
ModifiedDate = DateTime.Now,
AddDate = DateTime.Now,
Title = "Mr."
};
context.contacts.Add(contact);
int result = context.SaveChanges();
Console.WriteLine("Result :- "+ result.ToString());
}
The context class:
public class AddressBook : DbContext
{
public AddressBook()
{ }
public AddressBook(DbModel AddressBook)
: base(AddressBook)
{
}
public DbSet<Contact> contacts { get; set; }
public DbSet<Address> Addresses { get; set; }
}
and the connection string:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="AddressBook" providerName="System.Data.SqlClient"
connectionString="Data Source=MyMachine;Initial Catalog=AddressBook;
Integrated Security=True;MultipleActiveResultSets=True;"/>
</connectionStrings>
</configuration>
So, the database name is "AddressBook" and the error happens when I trying to add the contact object to the context. Am I missing anything here?
For VB.NET developers:
Add the following line to the Glabal.asax.vb file, at the end of method Application_Start()
Change ApplicationDbContext to your specific Db context.
Here I want to share another method that prevent the error of model backing when context changed is:
1) Open your DbContext File
2) Add namespace using Microsoft.AspNet.Identity.EntityFramework;
3) public MyDbContext() : base("name=MyDbContext") { Database.SetInitializer(new DropCreateDatabaseAlways()); }
Just run the followng sql command in SQL Server Management Studio:
For me, with the upgrade to 4.3.1, I just truncate the EdmMetaData table or just delete it outright.
It means that there were some changes on the context which have not been executed. Please run Add-Migration first to generate the changes that we have done (the changes that we might not aware) And then run Update-Database
For Entity Framework 5.0.0.0 - 6.1.3
You DO indeed want to do the following:
Yes, Matt Frear is correct. UPDATE -EDIT: Caveat is that I agree with others in that instead of adding this code to global.asax added to your DbContext class
As others mentioned this also is good for handling the unit testing.
Currently I am using this with Entity Framework 6.1.3 /.net 4.6.1