Mike
Mike

Reputation: 2601

Execute code first migration in code?

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.

Upvotes: 1

Views: 1329

Answers (2)

NSGaga
NSGaga

Reputation: 14302

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)

Upvotes: 2

David Swindells
David Swindells

Reputation: 641

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.

Upvotes: 0

Related Questions