Initializing the Efcore database by webhost extension modeEfcore Initialization of the database1. Defining the Webhostmigrationextensions Class
Public Static class webhostmigrationextensions{ Public StaticIwebhost migrationdbcontext<tcontext> ( ThisIwebhost host, Action<tcontext, iserviceprovider> seeder)whereTcontext:dbcontext {using(varScope = host. Services.createscope ()) {varServices = scope. serviceprovider;varLogger = Services. Getrequiredservice<ilogger<tcontext>> ();varContext = Services. Getservice<tcontext> ();Try{context. Database.migrate (); Seeder (context, services); Logger. Loginformation ($ "executes DbContext{typeof(Tcontext). Name} seed executed successfully! "); }Catch(Exception ex) {logger. LogError (ex,$ "executes DbContext{typeof(Tcontext). Name} seed execution failed! "); } }returnHost } }
Public class Applicationcontextseed{PrivateUsermanager<user> _usermanager;Public async Task seedasync(applicationdbcontext Context,iserviceprovider Service){if(!context. Users.any ()) {_usermanager = service. Getrequiredservice<usermanager<user>> ();varDefaultUser =NewUser {UserName ="[email protected]", Email ="[email protected]", normalizedemail="[email protected]", Normalizedusername ="Admin"};varresult =await_usermanager.createasync (DefaultUser,"pwd123456");if(!result. Succeeded) {Throw NewException ("Initializing database Failed"); } } } }
2. Calling in Buildwebhost
Public static void Main(string[] args){buildwebhost (args). Migrationdbcontext<applicationdbcontext> (context, services) = {NewApplicationdbcontextseed (). Seedasync (context, services). Wait (); }) . Run (); }
Initializing the Efcore database by webhost extension mode