Based on ASP. 2.0 WebAPI Background Framework (2)-EF core (MySQL) Codefirst database migration and Dependency injection

Source: Internet
Author: User

Overview

In the previous chapter, we simply built a three-tier architecture that relies on injection, but no real use, and we now use MySQL data to build frameworks based on EF Core's dbfirst.

    • Microsoft Dad Official Document: Use the new database to start using EF Core on ASP.
    • database table field naming conventions

Steps

1. Right click on the Entity project and click "Manage NuGet Packages"

  

2. Install the following three packages

    • Microsoft.entityframeworkcore installation Version: 2.1.0
    • Microsoft.EntityFrameworkCore.Tools installation Version: 2.1.0
    • POMELO.ENTITYFRAMEWORKCORE.MYSQL installation version: 2.1.0-rc1-final, Note that because the current stable version is still 2.0.1, if 2.0.1 is installed, it will fail in the database migration . So you should tick "include prerelease" in NuGet to install the latest 2.1.0-rc1-final

After the installation is complete, as shown in

  

3. Under the Entity---DataTable folder, add BaseEntity.cs, Note that the property values here do not follow the usual Pascal naming rules, but use the database naming design principles to name, meet reference link two.

     Public Abstract classbaseentity { Publicbaseentity () {create_time=DateTime.Now; }        /// <summary>        ///db version number, MySQL details reference;http://www.cnblogs.com/shanyou/p/6241612.html        /// </summary>        //1537269869//MySQL does not allow the byte[] type to be labeled Timestamp/rowversion, which uses the datetime type mate tag Concurrencycheck to achieve concurrency control[Concurrencycheck] PublicDateTime Row_version {Get;Set; } /// <summary>        ///creation Time/// </summary>         PublicDateTime Create_time {Get;Set; } }
baseentity

  

4. Under Entity---DataTable folder, add Dt_user.cs

     Public classdt_user:baseentity { PublicDt_user () {} [DataMember] [Key] Public Longuser_id {Get;Set; }        [Required] [MaxLength ( -)] [Description ("User name")]         Public stringUser_name {Get;Set; }        [Required] [MaxLength ( +)] [Description ("Password")]         Public stringUser_password {Get;Set; } }
Dt_user

5. In the MyContext.cs folder, Entity, add a data table

     Public classMycontext:dbcontext { PublicMycontext ():Base()        {        }         PublicMycontext (dbcontextoptions<mycontext>options):Base(options) {}Override protected voidonconfiguring (Dbcontextoptionsbuilder optionsbuilder) {Base.        Onconfiguring (Optionsbuilder); }        #regionData Sheet PublicDbset<dt_user> Dt_user {Get;Set; } #endregion    }
Mycontext

6. Under the Interfaces folder in the Bll, add the interface Idt_userservice.cs, you can notice

     Public InterfaceIdt_userservice:ibllservice<dt_user>    {        /// <summary>        ///Insert a new object/// </summary>        /// <returns></returns>Dt_user Insert (); /// <summary>        ///Get User Data table/// </summary>        /// <returns></returns>Ienumerable<dt_user>GetList (); }
Idt_userservice

 

7. Under the Bll-Implements folder, add Class Dt_userservice.cs

     Public classDt_userservice:bllservice<dt_user>, Idt_userservice {/// <summary>        ///used to instantiate a parent/// </summary>        /// <param name= "Rep" ></param>         PublicDt_userservice (idalservice<dt_user> dal):Base(DAL) {} PublicIenumerable<dt_user>GetList () {returnGetentities (R =true); }         PublicDt_user Insert () {Dt_user User=NewDt_user {user_name="test-"+NewRandom (). Next (10000), User_password=DateTime.Now.ToString ()}; returnAddentity (User,true); }    }
Dt_userservice8. Back to the Signup.cs file, add the database injection dependency and the service class service, each additional business class service must be added here aServices. AddTransient ()
     Public classStartup { PublicStartup (iconfiguration configuration) {Configuration=configuration; }         PublicIConfiguration Configuration {Get; } //This method gets called by the runtime. Use this method to add services to the container.         Public voidconfigureservices (iservicecollection services) {//Configuring Database Entity Dependency InjectionServices. adddbcontext<mycontext> (options = options. Usemysql (Configuration.getconnectionstring ("mysqlconnection")));            Diregister (services); Services.        Addmvc (); }        //Configuring Dependency Injection mapping Relationships         Public voidDiregister (iservicecollection services) {services. AddTransient (typeof(idalservice<>),typeof(dalservice<>)); Services. AddTransient (typeof(Idt_userservice),typeof(Dt_userservice)); }        //This method gets called by the runtime. Use this method to configure the HTTP request pipeline.         Public voidConfigure (Iapplicationbuilder app, Ihostingenvironment env) {if(env. Isdevelopment ()) {app.            Usedeveloperexceptionpage (); } app.        Usemvc (); }    }
Startup

9. Under Appsettings.json, add the MySQL database connection string

{  "ConnectionStrings": {    "mysqlconnection": "Server=localhost;database=loda_demo;uid= root;pwd=123456; "   },  " Logging ": {    false,    " Debug ": {      " LogLevel ":         { "Default": "Warning"      }    ,    "Console": {      "LogLevel": {        " Default ":" Warning "}}}  }
Appsettings.json

  

10. Database design completed, can be migrated, into the "Package management Console"

  

11. Note In the default project, switch to the Entity project, enter in the input box: add-migration init_1, Note that init_1 here is only the name of the current migration, the next time the database redesign, such as adding a user_ in Dt_user The age attribute, which needs to be re-migrated, is required to enter Add-migration Init_2, which must be different from the previous name, with the name randomly starting when prompted with "to undo this action, use Remove-migration." , you can see that there are some more files under the project when the migration succeeds.

  

  

  

12. Continue to enter Update-database, the following is the prompt for successful operation, we can open the MySQL database to see if the update has been successful.

13. Finally, test in the API and add the following code to the ValuesController.cs

[Route ("Api/[controller]")]     Public classValuescontroller:controller {PrivateIdt_userservice _userservice;  PublicValuescontroller (Idt_userservice userservice) {//Dependency Injection Gets an instance_userservice =UserService; }         PublicIactionresult Test () {_userservice.insert (); returnOk (_userservice.getlist ().        ToList ()); }    }
Valuescontroller

  

14. Run the program, open the page, get results, can go to the database to view, has been written to the database

  

  

15. Finally attach the frame file diagram

  

OK, the EF Core-based MySQL database migration project is over, and if you have other business, you can expand in accordance with the above Dt_user,dt_userservice,idt_userservice, with simulated user data, We're going to start thinking about how to authenticate the user. In the next chapter, we'll cover the use of JWT for authentication.

Based on ASP. 2.0 WebAPI Background Framework (2)-EF core (MySQL) Codefirst database migration and Dependency injection

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.