Asp. NET using Entityframeworkcore codefrist

Source: Internet
Author: User
1, first download the corresponding Microsoft official. NET Core SDK and runtime (Https://www.microsoft.com/net/download/core) according to individual needs

2, create an ASP. NET Core Project

3, create entity entities, users and roles


    public class User    {public        int Id {get; set;}        <summary>///Role ID///        </summary> public        int Roleid {get; set;}        Public virtual role Role {get; set;}        <summary>///state//        </summary> public        int status {get; set;}        <summary>///Login name///        </summary> public        string Login {get; set;}        <summary>///Login password///        </summary> public        string Pwd {get; set;}    }


    public class Role    {public        int Id {get; set;}        <summary>///Role name///        </summary> Public        string name {get; set;}        <summary>////        for multiple users of a role///        </summary> public        virtual icollection<user> users {get ; Set }    }

4, create DbContext


    public class Efdbcontext:dbcontext {public efdbcontext (dbcontextoptions<efdbcontext> options): Base        (options)        {} public dbset<role> Roles {get; set;}        Public dbset<user> Users {get; set;}            protected override void Onmodelcreating (ModelBuilder ModelBuilder) {Role (ModelBuilder);        User (ModelBuilder); } private void User (ModelBuilder ModelBuilder) {var userbuilder = Modelbuilder.entity<user&gt ;().            ToTable ("User"); Properties userbuilder.property (t = t.id).            Valuegeneratedonadd (); Userbuilder.property (t = t.roleid).            IsRequired (); Userbuilder.property (t = t.status).            IsRequired (); Userbuilder.property (t = t.login). IsRequired ().            Hasmaxlength (30); Userbuilder.property (t = t.pwd). IsRequired ().            Hasmaxlength (60);        Primary Key userbuilder.haskey (t = t.id);    Index userbuilder.hasindex (t = t.login); Relationships Userbuilder.hasone (t = t.role). Withmany (t = t.users).        Hasforeignkey (t = t.roleid); } private void Role (ModelBuilder ModelBuilder) {var rolebuilder = Modelbuilder.entity<role&gt ;().            ToTable ("Role"); Properties rolebuilder.property (t = t.id).            Valuegeneratedonadd (); Rolebuilder.property (t = t.name). IsRequired ().            Hasmaxlength (30);        Primary Key rolebuilder.haskey (t = t.id); }    }

5, create Dbinitializer, to create initial data


    public class Dbinitializer    {public        async static Task InitData (Efdbcontext context)        {            if (context. Database! = null && context. Database.ensurecreated ())            {                //Role Configuration                context. Roles.addrange (new role[]                {                    new role {name= "Super admin"},                    new role {name= "Administrator"}                );                Default User                context. Users.addrange (new user[]                {                    New user {roleid=1, login= "Administrator", pwd= "111111"},                    new user {Roleid =2, login= "admin", pwd= "111111"}                );                Await the context. Savechangesasync ();            }        }

6, modify the Startup class method

Add the following code to the Configureservices


dbcontextservices.adddbcontext<efdbcontext> (options = options. Usesqlserver (configuration.getconnectionstring ("defaultconnection"));

Adding within the Configure method


        Public async void Configure (Iapplicationbuilder app, Ihostingenvironment env, iloggerfactory loggerfactory)        {            Loggerfactory.addconsole (Configuration.getsection ("Logging"));            Loggerfactory.adddebug ();            App. Usemvc ();            Await Dbinitializer.initdata (app. Applicationservices.getservice<efdbcontext> ());        }

7, modify Appsettings.json


{"  ConnectionStrings": {    "defaultconnection": "Data source=.;i Nitial catalog=lnicecore;integrated security=sspi; "  },  " Logging ": {    " includescopes ": false,    " LogLevel ": {      " Default ":" Debug ",      " System ":" Information ",      " Microsoft ":" Information "}}  }

8, run the program, view the results

Related Article

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.