The model backing the 'ApplicationDbContext' context has changed since the database was created

前端 未结 21 1359
情话喂你
情话喂你 2020-12-02 07:24

First of all, I have not seen this error anywhere else and I guess it\'s not a replicate so please read the whole situation first.

Everything was working just fine

相关标签:
21条回答
  • 2020-12-02 07:48

    This error occurred to me when I made changes to my Model and did not make migration for the changes to update the database.

    If you have ever made changes to your model in Code First Migration Schema

    Don't forget to add migration

    add-migration UpdatesToModelProperites 
    

    The above command will read all the changes you have made in the model and will write it in the Up() and Down() methods.

    Then simply update your database using the below command.

    update-database
    

    This what worked for me.

    0 讨论(0)
  • 2020-12-02 07:49

    I spent many days to solve this issue, analyzed many different posts and tried many options and finally fixed. This 2 projects in my solution using EF code first migrations:

    • Console Application "DataModel" that mainly using as assembly which contains all my code first entities, DbContext, Mirgations and generic repository. I have included to this project separate empty local database file (in DataModel/App_Data folder) to be able generate migrations from Package Manager Console.
    • WebApi, which references to DataModel project and uses local database file from WebApi/App_Data folder, that not included in project

    I got this error when requested WebApi...

    My environment:

    • Windows 8.1 x64
    • Visual Studio 2015 Professional with Update 1
    • all my projects targeted for .NET Framework 4.6.1
    • EntityFramework 6.1.3 from NuGet

    Here I collected all the remarks you should pay attention and all conditions/requirements which must be met, to avoid mentioned exception :

    1. You should use only one version of EntityFramework Nuget package for all projects in your solution.
    2. Database, created by running sequentially all migration scripts should have the same structure/schema as you target database and correspond to entity model. Following 3 things must exactly correspond/reflect/match each other:
      • Your all migration script up to last
      • Current code first entity model state (DbContext, entities)
      • Target database
    3. Target database (mdf file) should be updated/correspond up to last migration script. Verify that "__MigrationHistory" table in your target database contains records for all migration scripts that you have, it means that all migration scripts was successfully applied to that database. I recommend you to use Visual Studio for generation correct code first entities and context that corresponds to your database, Project -> Add New Item -> ADO.NET Entity Data Model -> Code First from database: Of course, as an alternative, if you have no database you can write manually model (code first entities and context) and then generate initial migration and database.
    4. Name of connection string e.g. MyConnectionString in config file of startup project (Web.config/App.config):

      <configuration>
        <connectionStrings>
          <add name="MyConnectionString" connectionString="...">
        </connectionStrings>
      <configuration>
      

      should be equal to parameter passed in constructor of your DbContext:

       public partial class MyDbContext : DbContext
       {
          public MyDbContext()
             : base("name=MyConnectionString"){}
          ...
      
    5. Before using Package Manager Console, make sure that you are using correct database for update or generate migration and needed project is set as startup project of solution. For connect to database it will use connection string from that .config file, which in project, that is set as startup project.
    6. And the main, which fixed my issue: It is weird, but in my WebApi/bin folder DataModel.exe was old, not refreshed since last build. Since migrations was embedded in my assembly DataModel.exe then my WebApi updated database using old mirgations. I was confused why after updating database in WebApi it not corresponds to latest migration script from DataModel. Following code automatically creates(if not exists) or updates to latest migration local database in my WebApi/App_Data folder.

         public class WebApiApplication : System.Web.HttpApplication
         {
             protected void Application_Start()
             {
                 Database.SetInitializer(new MigrateDatabaseToLatestVersion<ODS_DbContext, Configuration>()); 
                 ...
      

      I tried clean and rebuild solution but it did not help, than I completely removed bin and obj folders from WebApi, deleted database files from WebApi/App_Data, built, restarted WebApi, made request to it, it created correct database - lazy initialization (using lines above), which corresponds to latest migration and exception didn't appear more. So, this may fix your problem:

      1. remove manually bin, obj folders from your startup project (which generates/updates your database)
      2. build your startup project or better clean and rebuild all you solution.
      3. recreate database by starting project (will execute lines above) or use Package Manager Console "update-database" command.
      4. manually check whether generated db and __MirgationHistory corresponds to latest migration script.
    0 讨论(0)
  • 2020-12-02 07:51

    This can happen when you change the data annotation of a model property. for example: adding [Required] to a property will cause a pending change in the database design.

    The safest solution is to run on the Package Manager Console:

    add-migration myMirgrationName
    

    which will display the exact changes in the Up() method. Therefore, you can decide if you really want to apply such changes via the:

    update-database
    

    Otherwise, you may just delete the latest migration from the __MigrationHistory table and from the Migrations folder the Solution Explorer.

    0 讨论(0)
提交回复
热议问题