InvalidOperationException Using EF Code First

Tags: Knockout, pubsub, observer, MVC, jQuery, Ajax, EF, Validation, FluentValidation, Visual Studio 2010, ASP.NET, JSON, FullCalendar, Silverlight, Architecture, Vista, IIS, Generics, NHibernate, WCF, RIA Services, Visual Studio 2008, SQL, STORM!, Nullable, ChannelFactory, netTCPBinding, VSPAT, responsive, design, HTML5, CSS3, MVC WebAPI, MVC 4, WebAPI, JQuery Mobile, ScheduleWidget, recurring events, Ninject, Pluggable, CQRS DDD, Windows

If you're using EF 4.1 "Code First" and make changes to your model you get the following error:

System.InvalidOperationException was unhandled by user code
Message=The model backing the 'MyContext' 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 DropCreateDatabaseIfModelChanges strategy will 
automatically delete and recreate the database, and optionally seed it
with new data.

I've mentioned this in previous blog posts and it's annoying. If you want to make it go away add the following line to your DbContext instance. Just remember, by doing this you're telling EF that you will be responsible for keeping the mapping between the database and your entities in sync.

public class MyContext : DbContext
{
    public DbSet<Foo> Foos { get; set; }
    public DbSet<Bar> Bars { get; set; }
 
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Conventions.Remove<System.Data.Entity
           .Infrastructure.IncludeMetadataConvention>(); 
    }
}