Nikita Goncharuk
Nikita Goncharuk

Reputation: 815

Asp.Net Core EF : How add Admin when initialize database

How to add Admin to the database, when creating this database or add using DBMS? I do not know which approach is more correct.

If I add through the code when initializing the database, where should I do this, in DbContext?

Upvotes: 1

Views: 1369

Answers (2)

galdin
galdin

Reputation: 14064

There is no correct approach as such. You may either do it:

  1. Using SQL Scripts - to run only when you run the scripts
  2. Using the EF Data Seeding API - to run only when you apply migrations
  3. In the main() - to run every time the application is run

You may do something like this in Main():

public static async Task Main(string[] args)
{
    // Build the application host
    var host = BuildWebHost(args);

    using(var scope = host.Services.CreateScope())
    {
        // Resolve the UserManager using the created scope 
        var usermanager = scope.ServiceProvider.GetService<UserManager<ApplicationUser>>();

        // TODO: Add default users if they don't already exist
    }

    // Run the application
    host.Run();
}

Upvotes: 2

Lajos Arpad
Lajos Arpad

Reputation: 76892

You did not give a lot of information about your situation, so I will answer in general terms.

If you have a single admin, then you might want to set its credentials to be inside your app config. You can also store it in your database. If your app can have multiple admins and their credentials might be changed, then you will need to store them into the database. A pretty common approach is to have a table where you store possible user roles, among them a record for admin and your users table should have a foreign key to the roles table.

It is good to have an installer application separately developed which will make sure that the application to be used will be usable on any environment. This app should be executed and should run all the scripts and program codes you need prior the usage of the application.

You will need some scripts for creating the database and the tables into it along with some records you might need, but the admin's credentials is best to be defined via the installer inside a program code, where the admin will enter his or her username and the program code will write that into the app config, if that's the approach you choose, or insert it into the database. If you have a script which will create the admin, then it is unsafe, as all the admins will have the very same password initially, which is a high security risk.

Upvotes: 2

Related Questions