265

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?

Tyson Williams
  • 1,630
  • 15
  • 35
Ashish Gupta
  • 14,869
  • 20
  • 75
  • 134
  • 1
    possible duplicate of [Entity Framework Code Only error: the model backing the context has changed since the database was created](http://stackoverflow.com/questions/3552000/entity-framework-code-only-error-the-model-backing-the-context-has-changed-sinc) – Gustav Bertram Feb 28 '14 at 09:29
  • 1
    Remove __MigrationHistory table from your database – Zahid Hasan Sep 17 '19 at 19:22
  • 1
    @ZahidHasan Definitely do not remove the __MigrationsHistory table unless you fully understand the purpose of the __MigrationsHistory and are willing to manually reconcile the difference between the code and the database, and make the same changes in production. – Aaron Queenan Sep 23 '20 at 06:04

27 Answers27

420

Now it's:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    Database.SetInitializer<YourDbContext>(null);
    base.OnModelCreating(modelBuilder);
}

in your YourDbContext.cs file.

Youngjae
  • 24,352
  • 18
  • 113
  • 198
Matt Frear
  • 52,283
  • 12
  • 78
  • 86
  • I've changed my production db manually and turned off the migration and it works, Thanks – Mohsen Afshin Sep 10 '12 at 21:05
  • Note: I had to make it `Database.SetInitializer(null);`. – user1477388 Feb 06 '13 at 20:53
  • 13
    Ps, this goes in Global.asax Application_Start() – BritishDeveloper Feb 23 '13 at 00:08
  • 50
    Better than Global.asax is to put this in the constructor of your DbContext class. That way it works for every site using the context rather than just the one site controlled by the Global.asax file. – Corin Mar 25 '13 at 17:03
  • 7
    Probably best to put it in the static contructor of the context class so it's only called once - as in this example video: http://msdn.microsoft.com/en-us/data/jj572367 – Christian Fredh Jul 11 '13 at 10:38
  • 3
    It should be placed inside protected override void OnModelCreating(DbModelBuilder modelBuilder) { Database.SetInitializer(null); base.OnModelCreating(modelBuilder); } – Chris Voon Apr 19 '14 at 03:44
  • I was getting same error for my Code first Model. It fixed the same way explained above. – Nps Jul 08 '14 at 05:06
  • Is it possible to leading to the loss of data? I don't want my data be damaged or loss. – x19 Oct 21 '14 at 16:28
  • @Toolkit this question and this answer was written years before EF Code First came out – Matt Frear Oct 22 '15 at 11:06
  • @MohsenAfshin u said "I've changed my production db manually and turned off the migration and it works" how to turned off the migration plzz guide me. thanks – Monojit Sarkar Sep 13 '16 at 14:50
  • @MattFrear Dear your solutions was perfectly for me. Can you explain what this command does behind the scene a little, Thank you so much. – Kewin Rather Jan 12 '17 at 07:38
  • This worked for me under EF 6. I have an importer which creates a SQL View when the Db is created. This view cannot be set as a DbSet on this context so the Table in question is removed....A second context is added with my Models with a different Context name and the View table is added to the DbSet. Using the SetInitializer stops this throwing an error on this table when you try to access the Db. – David Graham Oct 29 '17 at 16:24
  • Thanks for this solution. I have a SQL Server View used in the application to export to Excel using EPPlus. The SQL View is treated as a DB table in the application and I manually create it using SSMS (not Code First). I use a separate DBContext for the export from the SQL View. Your Database.SetInitializer addition to my DBContext got rid of the exception, and I don't have to do a sync-up EF Code First Migration! – Greg Barth Jun 06 '23 at 20:55
140

Here's some information from Scott Gu's Blog posted by Jeff on what's actually taking place:

For those who are seeing this exception:

"The model backing the 'Production' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance."

Here is what is going on and what to do about it:

When a model is first created, we run a DatabaseInitializer to do things like create the database if it's not there or add seed data. The default DatabaseInitializer tries to compare the database schema needed to use the model with a hash of the schema stored in an EdmMetadata table that is created with a database (when Code First is the one creating the database). Existing databases won’t have the EdmMetadata table and so won’t have the hash…and the implementation today will throw if that table is missing. We'll work on changing this behavior before we ship the fial version since it is the default. Until then, existing databases do not generally need any database initializer so it can be turned off for your context type by calling:

Database.SetInitializer<YourDbContext>(null);

Jeff

Randy
  • 1,955
  • 2
  • 15
  • 24
  • 9
    I tried this today, and I no longer get "The model has changed", instead I get "Invalid object name 'dbo.Table'" – Stefan Bergfeldt Sep 19 '12 at 08:00
  • 3
    Jeff wanted this to be a workaround but it has been more than two years since and SetInitializer to null is still required. right? So could someone please explain how this fits in to the migration workflow. – kroiz Jan 23 '14 at 07:50
  • +1 This issue was causing my app to fail even though the underlying model wasn't changing when checked into Azure/VisualStudio Online – James Fleming Feb 19 '14 at 20:45
  • I encountered the same issue even today with EF 6 and this solved my problem. I don't have an initializer explicitly created or specified in my config either. I just added this to my Global.asax Application_Start() and problem is solved. – jakejgordon May 24 '14 at 02:43
  • 4
    @jakejgordon: Me too with the EF6 but if it is in Global.asax, it only fixes the problem when running the website. If you have unit tests, you're OOL. Better to put it in the constructor of YourDbContext. That fixes it for every project, including the website and test projects. – Rap Jul 09 '14 at 14:51
  • Thank you so much for this! I've been getting this error for quite a while when trying to do simple, normal CF migrations. I'm using EF 6 though and it seems crazy to me that it still has this problem... – levininja Nov 10 '14 at 19:56
  • 1
    IMO, this answer should be scored higher since it actually explains *why* we need to add this line of code. Thank you. – Paul Sep 18 '15 at 02:02
  • 1
    @StefanBergfeldt if you or anyone get the `Invalid object name 'dbo.Table` check your connection string attachDbFilename and initial catalog – benscabbia Jan 12 '17 at 07:28
44

For Entity Framework 5.0.0.0 - 6.1.3

You DO indeed want to do the following:

1. using System.Data.Entity;   to startup file (console app --> Program.cs / mvc --> global.asax
2. Database.SetInitializer<YourDatabaseContext>(null);

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

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // other code 
    Database.SetInitializer<YOURContext>(null);
    // more code here.
}

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

I will come back to provide a CORE snippet in the near future.

Tom Stickel
  • 19,633
  • 6
  • 111
  • 113
  • 1
    Thank you! Program.cs definitely works for consoles. – JsAndDotNet Oct 02 '14 at 20:07
  • But when you first time initialize your database then it is not creating database if I put setinitializer null at onModelCreating method. Any thoughts ? Eventhoug i do using (var context = Activator.CreateInstance()) { context.Database.Initialize(true); } – Rupesh Kumar Tiwari Aug 04 '15 at 16:41
  • I need to find my code that I would use that I would sometimes comment out a line and swap ... I don't recall off hand the issue, I need to look. – Tom Stickel Aug 04 '15 at 17:37
  • 1
    The best solution. It cause my solution to run, and I have no idea what the ramifications are. Commit and deploy. – Svend Jan 31 '19 at 09:48
36

Just run the followng sql command in SQL Server Management Studio:

delete FROM [dbo].[__MigrationHistory]
Shafqat
  • 1,104
  • 1
  • 11
  • 17
  • 3
    You saved my life! Thank you. – Marek Dorda Sep 04 '18 at 17:04
  • 4
    Do not remove the __MigrationsHistory table unless you fully understand the purpose of the __MigrationsHistory and are willing to manually reconcile the difference between the code and the database, and make the same changes in production. – Aaron Queenan Sep 23 '20 at 06:06
31

This fix no longer works after CTP5.

You have to do Database.SetInitializer<YourContext>(null);

Meenal
  • 2,879
  • 5
  • 19
  • 43
chrisortman
  • 1,514
  • 15
  • 22
18

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;
   }
}
Ashish Gupta
  • 14,869
  • 20
  • 75
  • 134
  • 13
    This is no longer possible with later versions of EF, also ``modelBuilder.Conventions.Remove();`` doesn't help the situation. DbDatabase.SetInitialzer(null); does work. – JTew Dec 07 '12 at 01:41
  • @TomStickel - I agree. Marked https://stackoverflow.com/a/6143116/255562 as the answer. – Ashish Gupta Jul 10 '17 at 16:24
16

Or you can put this line in your Global.asax.cs file under Application_Start():

System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<ProjectName.Path.Context>());

Make sure to change ProjectName.Path.Context to your namespace and context. If using code first this will delete and create a new database whenever any changes are made to the schema.

dwp4ge
  • 1,963
  • 22
  • 27
8

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.
Sergey Kulgan
  • 1,215
  • 1
  • 12
  • 12
5

For me, with the upgrade to 4.3.1, I just truncate the EdmMetaData table or just delete it outright.

Rob Koch
  • 1,523
  • 3
  • 18
  • 26
  • I updated to 4.3.1 and then just renamed the EdmMaetaData table. I can now make changes to the model as needed and no more annoying error messages about the model backing blah blah. – Ashok Padmanabhan Jun 10 '12 at 09:39
3

For VB.NET developers:

Add the following line to the Glabal.asax.vb file, at the end of method Application_Start()

Database.SetInitializer(Of ApplicationDbContext)(Nothing)

Change ApplicationDbContext to your specific Db context.

2

I had this issue and it turned out that one project was pointing to SQLExpress but the one with the problem was pointing to LocalDb. (in their respective web.config). Silly oversight but worth noting here in case anyone else is troubleshooting this issue.

Stuart Dobson
  • 3,001
  • 4
  • 35
  • 37
2

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

Kerisnarendra
  • 877
  • 9
  • 14
2

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.

Richard Barker
  • 1,161
  • 2
  • 12
  • 30
1

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

        }
flobadob
  • 2,804
  • 2
  • 22
  • 23
1

This error can indicate an issue with your connection string and whether your connection string name matches the Database context declaration.

I had this error because I had named the local database wrongly (silly mistake) and the name of the connection string in web.config of "DefaultConnection" did not match the MyDbContext i.e.

public MyDbContext(): base("DefaultConnection")
{}


<connectionStrings>
    <add name="DefaultConnection" ...
  </connectionStrings>
DanAbdn
  • 7,151
  • 7
  • 27
  • 38
  • This should be the accepted answer!! Everyone else's answer here wasted an hour of my time this is the only one that killed the error message without barely having to change anything. – AndrewBenjamin Nov 02 '20 at 07:02
1

Good suggestion, however, nt so accurate in all cases. I figure one out. Please you need to make sure you run "enable-migrations" using PM windows in Visual Studio, and Migration folder would be added to you project.

Make sure the two c# class files added to the folder on will contain all your models and their respective properties.

If you have all that build the solution, and publis for deployment.

The logic is that the existing metadata cannot be overwritten because your application has no metadata to replace the current. As a result you are getting this error "The model backing the context has changed since the database was created"

Kay Ken
  • 11
  • 1
1

Just in case someone has the same scenario as mine.

I have database first EF and at the same time using the asp.net identity

so I have two connectionStrings in my webconfig, and there is no problem with that. It happened that I created/run the scripts to generate manually the asp.net identity tables which I should not.

so DROP first all the asp.net identity tables created by you manually/from scripts.

DROP TABLE __MigrationHistory
DROP TABLE AspNetRoles
DROP TABLE AspNetUserClaims
DROP TABLE AspNetUserLogins
DROP TABLE AspNetUserRoles
DROP TABLE AspNetUsers
Francis Saul
  • 728
  • 2
  • 16
  • 37
1

None of these solutions would work for us (other than disabling the schema checking altogether). In the end we had a miss-match in our version of Newtonsoft.json

Our AppConfig did not get updated correctly:

<dependentAssembly>
   <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
  </dependentAssembly>

The solution was to correct the assembly version to the one we were actually deploying

<dependentAssembly>
   <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="10.0.0.0" />
  </dependentAssembly>
AcidPAT
  • 709
  • 7
  • 13
0

After some research on this topic, I found that the error is occured basically if you have an instance of db created previously on your local sql server express. So whenever you have updates on db and try to update the db/run some code on db without running Update Database command using Package Manager Console; first of all, you have to delete previous db on our local sql express manually.

Also, this solution works unless you have AutomaticMigrationsEnabled = false;in your Configuration.

If you work with a version control system (git,svn,etc.) and some other developers update db objects in production phase then this error rises whenever you update your code base and run the application.

As stated above, there are some solutions for this on code base. However, this is the most practical one for some cases.

Mahmut C
  • 427
  • 4
  • 6
0

I am reading the Pro ASP.NET MVC 4 book as well, and ran into the same problem you were having. For me, I started having the problem after making the changes prescribed in the 'Adding Model Validation' section of the book. The way I resolved the problem is by moving my database from the localdb to the full-blown SQL Server 2012 server. (BTW, I know that I am lucky I could switch to the full-blown version, so don't hate me. ;-))) There must be something with the communication to the db that is causing the problem.

  • How do you know it's the communication to the db, and not for example its metadata? – flup Jan 24 '13 at 20:31
  • 2
    Sorry for the late response. It turns out its not a communication issue at all! Recreating the db just masked the problem, because I got the same problem again! A __Migrationxxx (can't recall the exact name of the table because I just removed it) is created by ef. Just delete it and you should be all good. – J3Speaks Feb 08 '13 at 16:00
  • @MyJ3 All people spouting all these friggin lines and lines of code. This all I needed! Deserves to be an answer (Optional Scenario). – Terrance00 Aug 17 '15 at 14:56
  • @Terrance00 Thanks! – J3Speaks Jan 31 '19 at 22:45
0

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

Database.SetInitializer<YourDatabaseContext>(
 new DropCreateDatabaseIfModelChanges<YourDatabaseContext>());
p.campbell
  • 98,673
  • 67
  • 256
  • 322
oeddy
  • 35
  • 4
0

Check this following steps

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

2.

  1. your Context class name should match with check it
Siva
  • 21
0

Try using Database SetInitializer which belongs to using System.Data.Entity;

In Global.asax

protected void Application_Start()
{
    Database.SetInitializer(new DropCreateDatabaseIfModelChanges<yourContext>());
}

This will create new database everytime your model is changed.But your database would be empty.In order to fill it with dummy data you can use Seeding. Which you can implement as :

Seeding ::

protected void Application_Start()
{
    Database.SetInitializer(new AddressBookInitializer());
                ----rest code---
}
public class AddressBookInitializer : DropCreateDatabaseIfModelChanges<AddressBook>
{
    protected override void Seed(AddressBook context)
    {
        context.yourmodel.Add(
        {

        });
        base.Seed(context);
    }

}
SinghMavi
  • 1
  • 3
0

It's weird, but all answers here were useless for me. For me worked initializer

MigrateDatabaseToLatestVersion

Here's my solution (I know, it can be much simplier, but it's how I use it):

class MyDbMigrateToLatest : MigrateDatabaseToLatestVersion<MyDbContext, Configuration>
{
}

public class MyDbContext: DbContext
{
    public MyDbContext() : base("DbName")
    {
        SetInitializer();
    }

    public MyDbContext(string connString) : base(connString)
    {
        SetInitializer();
    }

    private static void SetInitializer()
    {
        if (ConfigurationManager.AppSettings["RebuildDatabaseOnStart"] == "true")
            Database.SetInitializer(new MyDbInitializerForTesting());
        else
            Database.SetInitializer(new MyDbMigrateToLatest());
    }
}

public sealed class Configuration : DbMigrationsConfiguration<MyDbContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
    }

    protected override void Seed(MyDbContext context)
    {
        // Whatever
    }
}

MyDbInitializerForTesting just inherits from DropCreateDatabaseAlways so in some specific case (testing), whole database is rebuilded. Otherwise it's migrated to latest version.

My source: https://msdn.microsoft.com/en-us/data/jj591621.aspx#specific

Tomino
  • 5,969
  • 6
  • 38
  • 50
0

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

Julia Savinkova
  • 573
  • 8
  • 18
0

Create custom context initializer:

public class MyDbContextInitializer : MigrateDatabaseToLatestVersion<MyDbContext, Migrations.Configuration>
{
    public override void InitializeDatabase(MyDbContext context)
    {
        bool exists = context.Database.Exists();

        base.InitializeDatabase(context);

        if (!exists)
        {         
            MyDbSeed.Seed(context);
        }
    }       
}

Note that Migrations.Configuration is a class generating by migration command line in Package Manager Console. You may need to change internal to public modifier of the Migrations.Configuration class.

And register it from your OmModelCreating:

public partial class MyDbContext : DbContext
{

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer<MyDbContext>(new MyDbContextInitializer());

        //other code for creating model
    }
}
Tomas Kubes
  • 23,880
  • 18
  • 111
  • 148
-3

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()); }

  • That would delete your entire database. Maybe that's okay for development, but when that code accidentally gets published to production and deletes everything, nobody will be happy about it. – Aaron Queenan Sep 23 '20 at 06:12