1

I'm working on a multi-tenant MVC 4 application and I'm going with the one schema per customer approach. I'd like to run the database migrations in code when a customer signs up. Is this possible using EF 5/Code First Migrations?

So when a customer signs up, I'll create an account in dbo. I'll then check if their subdomain exists as a schema in the database, if not, I'll create the schema and ideally run the migrations.

Thanks!

Clarification

When I create the new schema for the customer in the database, I want to run the migrations for that new schema. So for example,

I'll have schema1.Products and schema2.Products.

Mike
  • 2,561
  • 7
  • 34
  • 56

2 Answers2

2

If I'm getting it right what you want...

You could use something like this

var migrator = new DbMigrator(new Configuration());
if (migrator.GetPendingMigrations().Any())
    migrator.Update();  

Or even better you may want to create your own initializer - e.g. check these posts of mine...

What is the correct use of IDatabaseInitializer in EF?

How to create initializer to create and migrate mysql database?


The problem I see with your approach is that'd you'd have to 'separate' the account model/database - and the one that you're trying to migrate. Since you mentioned multi-tenant that may already be the case.

But I guess you could also crete the 'base entities' for accounts etc. - and then migrate the rest on top. That's a bit complex scenario - the model is created once (per connection) on start (first use) and cached from then on. So the only for that would be to restart reload, I think (don't hold my word for it, just thinking out loud here)

Community
  • 1
  • 1
NSGaga-mostly-inactive
  • 14,052
  • 3
  • 41
  • 51
  • I think what I have to do is to use migrations for the base entities like Accounts and then run SQL scripts to create the schema and other tables specific to the schema. It would be nice to have two different migration classes. – Mike May 01 '13 at 18:58
  • that effectively answers your main Q (with the custom initializer) - however the rest is too specific, I can hardly tell you anything sensible more than I already did. As for `two different...`, migrations are 'singleton' mostly (migrations==your Configuration + scripts + connection + Db + __MigrationHistory sys table). I think you can have two in two libs, but you'd have to have 'two db-s' (cause of the migration table in db). It's not multi-tenant (it comes in EF6). – NSGaga-mostly-inactive May 02 '13 at 13:31
0

Not sure if this is what you're asking for, you can run code migrations from command line:

packages\EntityFramework.5.0.0\tools\migrate.exe Example.dll /startUpDirectory:Example\bin

So in theory you could call this whenever a new customer signed up.

David Swindells
  • 641
  • 1
  • 12
  • 28