DeepSpace101
DeepSpace101

Reputation: 13722

EF 5 code-first migrations with multiple contexts?

Our application has two contexts into the same application database. Each context is cleanly divided across their separation of concerns.

Now it seems that if I have two contexts, Context1 and Context2 and if I only change Context2's classes, EF 5.0 thinks even Context1 has changed. That seems to confuse EF 5.0 and seems to trigger migrations on both. After that incorrect detection, the resulting migrations are also inconsistent. We at a weird dead end due to that and our own oversight and most likely have to rebuild the entire db all over again :( (the up and down paths are inconsistent)

So, questions:

  1. Does EF 5.0 support model-change detection and migrations for multiple contexts? I read this EF 4.3 stackoverflow question and also this MSFT post by Rowan before considering asking this here. I don't think this is a repeat since EF 4.3 => EF 5.0 improvements target code-first and migrations.
  2. If not, when are you guys (MSFT/Rowan!) planning to support it?

Thx

Background story details (can be skipped):

We carefully set both 'schemas' via with code-first fluent api, added test data, tested it out and then added 'live' (alpha stage) data. Context1 bore critical 'live' info so we left it untouched and I then modified the 2nd context (context2 here) by adding a new member to the code first class (new column in table in db terms). When I ran the app, it seems to have detected BOTH as changed! At our end, thinking the unchanged Context1 won't be called, we didn't comment out the Database.SetInitializer<Context1>(new DropCreateDatabaseIfModelChanges<Context1>()); we added during bringup. So it wiped out our critical now-grown tables! Yes, we should have taken it out as simply locking down the class definition wasn't good enough.

Upvotes: 4

Views: 5104

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364249

Multiple context to single database doesn't work very well yet but there should be a simple workaround. Create one more context which will never be used in your application logic except the migration. Add entity mapping for all entities from other contexts to this central context used for database creation / migration.

Btw. EF is open source so you can contribute and add support for multiple context yourselves.

Upvotes: 4

Related Questions