40

I'm working with EF 4.3 and have a context which needs to talk to a database which was generated by another library using EF Code First 4.3. The context is throwing an exception stating

The model backing the 'Context' context has changed since the database was created. Consider using Code First Migrations to update the database

In EF 4.1 this could be diabled by removing the IncludeMetadataConvention from the ModelBuilder. However, in 4.3 this convention has been deprecated and no longer has an effect.

How can I have an EF 4.3 context talk to an EF 4.3-generated database built by a different context? The only option I've found (which is far from ideal) is to delete the metadata table, thereby causing both contexts to assume the database was not build by EF.

PS: I know this scenario is likely to raise questions about why I need to do this; I know it's far from ideal, but rest assured it's a problem I need to solve and have limited options to work with laterally.

Masoud
  • 8,020
  • 12
  • 62
  • 123
STW
  • 44,917
  • 17
  • 105
  • 161

2 Answers2

70

Setting the initializer to null will skip the model compatibility check.

Database.SetInitializer<MyContext>(null);
bricelam
  • 28,825
  • 9
  • 92
  • 117
  • 1
    Where do you put this? – jep Jan 22 '14 at 03:15
  • 4
    A static constructor on your context seems to work pretty well for most applications. – bricelam Jan 23 '14 at 17:56
  • @deepakgates I have it in my Context constructor. – jonas Oct 15 '14 at 08:06
  • Add `using System.Data.Entity` if this line shows error. – Leonel Sanches da Silva Jan 04 '16 at 20:41
  • If you find this isn't working as expected then check the EF section of your config file. Make sure your context has disableDatabaseInitialization="true". I lost far too many hours to this and no one mentions it in their answers on here. More info on this setting can be found on the bottom of https://msdn.microsoft.com/en-us/data/jj556606 – Brian Surowiec Sep 11 '17 at 07:14
15

For EF 4.3 or higher

Database.SetInitializer<MLTServerWatcherContext>(null);

Or if using older version of EF

modelBuilder.Conventions.Remove<IncludeMetadataConvention>();

(I know he said he are using EF 4.3, but i think it's good to show this option too)

Diego Vieira
  • 843
  • 2
  • 8
  • 13