The model backing the context has chang

2019-01-01 02:49发布

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?

27条回答
只靠听说
2楼-- · 2019-01-01 03:29

I had the same issue - re-adding the migration and updating the database didn't work and none of the answers above seemed right. Then inspiration hit me - I'm using multiple tiers (one web, one data, and one business). The data layer has the context and all the models. The web layer never threw this exception - it was the business layer (which I set as console application for testing and debugging). Turns out the business layer wasn't using the right connection string to get the db and make the context. So I added the connection string to the app config of the business layer (and the data layer) and viola it works. Putting this here for others who may encounter the same issue.

查看更多
弹指情弦暗扣
3楼-- · 2019-01-01 03:30

Just found out the answer and thought of updating here. Just need to do the following.

public class AddressBook: DbContext
{
   protected override void OnModelCreating(ModelBuilder modelBuilder)
   {
    modelBuilder.IncludeMetadataInDatabase = false;
   }
}
查看更多
荒废的爱情
4楼-- · 2019-01-01 03:30

Check this following steps

  1. Database.SetInitializer(null); -->in Global.asax.cs

2.

  1. your Context class name should match with check it
查看更多
呛了眼睛熬了心
5楼-- · 2019-01-01 03:32

I use the Database.CompatibleWithModel method (available in EF5) to test if the model and DB match before I use it. I call this method just after creating the context...

        // test the context to see if the model is out of sync with the db...
        if (!MyContext.Database.CompatibleWithModel(true))
        {
            // delete the old version of the database...
            if (File.Exists(databaseFileName))
                File.Delete(databaseFileName);
            MyContext.Database.Initialize(true);

            // re-populate database

        }
查看更多
一个人的天荒地老
6楼-- · 2019-01-01 03:32

Modify Global.asax.cs, including the Application_Start event with:

Database.SetInitializer<YourDatabaseContext>(
 new DropCreateDatabaseIfModelChanges<YourDatabaseContext>());
查看更多
看风景的人
7楼-- · 2019-01-01 03:33

I had the same problem when we used one database for two applications. Setting disableDatabaseInitialization="true" in context type section works for me.

<entityFramework>
<providers>
  <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
<contexts>
  <context type="PreferencesContext, Preferences" disableDatabaseInitialization="true">
    <databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[PreferencesContext, Preferences], [Migrations.Configuration, Preferences]], EntityFramework" />
  </context>
</contexts>

See more details https://msdn.microsoft.com/en-us/data/jj556606.aspx

查看更多
登录 后发表回答