2

I have an application that when user registers, there will be a new database created for that specific user. My questions: Is this the proper way to create the database dynamically based on EF Core 2.0 Code First and apply migrations?

Assuming I have my context: CustomDbContext, and in the Registration Action I have like this:

    [HttpPost]
    public async Task<IActionResult> Register(RegisterViewModel model)
    {           

        //register user logic here

        using (CustomDbContext ctx = new CustomDbContext())
        {
             await ctx.Database.EnsureCreatedAsync();   
             await ctx.Database.MigrateAsync();
        }           

        return RedirectToPage("/Index");
    }

Does await ctx.Database.EnsureCreatedAsync(); also apply the migrations? or I do need to run await ctx.Database.MigrateAsync(); to apply them?

1
  • Please don't force tags into the question title. Also read this help center article What are tags, and how should I use them? to find out how to use tags correctly Commented Nov 12, 2017 at 9:42

1 Answer 1

2
ctx.Database.MigrateAsync(); 

Will create the database as well as apply migrations. No need to do both.

On the side, that probably shouldn’t be called in Controller action, but somewhere in DataAccess layer, ideally called less often to make performance better. I would suggest to do that when web application is first started, or recycled etc.

Sign up to request clarification or add additional context in comments.

7 Comments

How will you do it in this scenario that the database needs to be done at registration? Should I do it as a job instead?
Just noticed the intellisense on the MigrateAsync(): Asynchronously applies any pending migrations for the context to the database. Will create the database if it does not already exist. Note that this API is mutually exclusive with DbContext.Database.EnsureCreated(). EnsureCreated does not use migrations to create the database and therefore the database that is created cannot be later updated using migrations.
Check DBInitializer type here: learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro. They do EnsureCreated(), not migrations, but rest is same.
Isn't this used when populating the database with test data? I think the best scenario will be handle the creation using a queue or something like this. When user register, add a message to queue and then a job will process the messages and migrate the context database like in the code above. I don't need to add sample data or something like that.
Still you want to separate it from Actions and call it from Startup.cs when app is started as opposed to in each action
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.