Initializing the Efcore database by webhost extension mode

Source: Internet
Author: User
Tags webhost

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.