Set up a web API for ASP. NetCore2.0 that connects to the MySql three-tier architecture,
Here we use a three-tier architecture to build a WebApi project that connects to the ASP. netCore template of MySql.
First, add a WebApi Project (ASP. NetCore version)
Right-click solution> Create Project>
Select Web> ASP. NET Core Web application (. NET Core)
Select Web API
The directory structure is as follows:
Add Entity layer Entity
Right-click Add> new project>. Net Core class library
Added directory structure
BaseEntity:
Using System; using System. collections. generic; using System. componentModel. dataAnnotations; using System. runtime. serialization; using System. text; namespace Entity. core {// <summary> // basic attributes of the DB table /// </summary> public abstract class BaseEntity <T> {public BaseEntity () {CreteTime = DateTime. now ;}//< summary >/// primary Key Id /// </summary> [DataMember] [Key] public T Id {get; set ;} /// <summary> // database version number. For more information about Mysql, see; http://www.cnblogs.com/shanyou/p/6241612.html /// </summary> // 1505898472 // Mysql does not allow TimeStamp/RowVersion to be marked on the byte [] type, here, the DateTime type is used together with the Mark ConcurrencyCheck to achieve concurrency control [ConcurrencyCheck] public DateTime RowVersion {get; set ;} /// <summary> /// creation time /// </summary> public DateTime CreteTime {get; set ;}}}
Product:
Using Entity. core; using System. collections. generic; using System. componentModel. dataAnnotations; using System. text; namespace Entity. table {// <summary> /// commodity class /// </summary> public class Product: baseEntity <long >{/// <summary> /// Name // </summary> [StringLength (20)] [Required] public string Name {get; set ;} /// <summary> /// Description /// </summary> [StringLength (500)] [Required] public string Description {get; set ;} /// <summary> /// category /// </summary> [Range (1, int. maxValue)] public int Category {get; set ;}/// <summary> // Original Price /// </summary> [Required] public decimal Price {get; set ;}/// <summary> /// current price /// </summary> public decimal Discount {get; set ;}}}Add data layer DAL:
Right-click Add> new project>. NET Core class library
Add reference:
Microsoft. EntityFrameworkCore (you can also add Microsoft. AspNetCore. All, but it will be a waste of useful functions)
Microsoft. EntityFrameworkCore. Tools (supported for migration)
For detailed usage rules of Pomelo. EntityFrameworkCore. MySql (supported by Mysql), see: Pomelo. EntityFrameworkCore. MySql usage rules
<Project Sdk = "Microsoft. NET. sdk "> <PropertyGroup> <TargetFramework> netcoreapp2.0 </TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include =" Microsoft. entityFrameworkCore "Version =" 2.0.0 "/> <PackageReference Include =" Pomelo. entityFrameworkCore. mySql Version = "2.0.0-rtm-10062"/> <! -- Required for migration support --> <PackageReference Include = "Microsoft. EntityFrameworkCore. Tools" Version = "2.0.0" PrivateAssets = "All"/> </ItemGroup> <! -- Required for migration support --> <DotNetCliToolReference Include = "Microsoft. entityFrameworkCore. tools. dotNet "Version =" 2.0.0 "/> </ItemGroup> <ProjectReference Include = ".. \ Entity. csproj "/> </ItemGroup> </Project>
Add DbContext data context
Using Entity. table; using Microsoft. entityFrameworkCore; using System. collections. generic; using System. linq; using System. text; namespace DAL {public class ProductContext: DbContext {// https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/complex-data-model public ProductContext (DbContextOptions <ProductContext> options): base (options) {// perform encryption and decryption on the database connection string} public DbSet <Product> Courses {get; set;} protected override void OnModelCreating (ModelBuilder modelBuilder) {base. onModelCreating (modelBuilder );}}}
Reference the newly created DAL class library in the ASP. Net Core API project
Add Service Layer
Right-click Add> new project>. NetCore class library
Add reference:
Add Entity and DAL references, and then add third-party Data Warehouse Microsoft. EntityFrameworkCore. UnitOfWork (latest)
<ItemGroup> <PackageReference Include="Microsoft.EntityFrameworkCore.UnitOfWork" Version="2.0.1" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\DAL\DAL.csproj" /> <ProjectReference Include="..\Entity\Entity.csproj" /> </ItemGroup>
The file directory is as follows:
IProductService:
using System;using System.Collections.Generic;using System.Text;namespace Service.ProductService{ public interface IProductService { string Test(); }}
ProductService:
Using Entity. table; using Microsoft. entityFrameworkCore; namespace Service. productService {public class ProductService: IProductService {private readonly IUnitOfWork _ unitOfWork; public ProductService (IUnitOfWork unitOfWork) {_ unitOfWork = unitOfWork;} public string Test () {var repo = _ ofunitwork. getRepository <Product> (); repo. insert (new Product {Category = 1, Description = "This Product is purchased in Australia and cannot be bought at any cost. ", Discount = (decimal) 899.21, Price = (decimal) 98.2, Name =" australian kangaroo powder ",}); _ unitOfWork. saveChanges (); // submit it to the database var result = repo. getFirstOrDefault ()?. Description ?? String. Empty; return result ;}}}
Add the newly created Service class library reference using ASP. Net Core API
<ItemGroup> <ProjectReference Include="..\DAL\DAL.csproj" /> <ProjectReference Include="..\Service\Service.csproj" /> </ItemGroup>
The complete csproj is as follows:
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>netcoreapp2.0</TargetFramework> </PropertyGroup> <ItemGroup> <Folder Include="wwwroot\" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" /> </ItemGroup> <ItemGroup> <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\DAL\DAL.csproj" /> <ProjectReference Include="..\Service\Service.csproj" /> </ItemGroup></Project>
Use service in Controller
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Service.ProductService;
namespace ASP.Net_Core_API.Controllers{ [Route("api/[controller]")] public class ValuesController : Controller { private IProductService _productService; public ValuesController(IProductService productService) { _productService = productService; } // GET api/values [HttpGet] public IEnumerable<string> Get() { var result = _productService.Test(); return new string[] { "value1", result }; } }}
Mysql support and corresponding injection services are added to the Startup File, as well as UnitOfWork support.
The complete file is as follows:
Using System; using System. collections. generic; using System. linq; using System. threading. tasks; using Microsoft. aspNetCore. builder; using Microsoft. aspNetCore. hosting; using Microsoft. extensions. configuration; using Microsoft. extensions. dependencyInjection; using Microsoft. extensions. logging; using Microsoft. extensions. options; using Microsoft. entityFrameworkCore; using Entity. table; using DAL; using Service. productService; namespace ASP. net_Core_API {public class Startup {public Startup (IConfiguration configuration) {Configuration = configuration;} public IConfiguration Configuration {get;} // This method gets called by the runtime. use this method to add services to the container. public void ConfigureServices (IServiceCollection services) {services. addDbContext <ProductContext> (options => options. useMySql (Configuration. getConnectionString ("MySqlConnection"); // Add Mysql support services. addUnitOfWork <ProductContext> (); // Add UnitOfWork support services. addScoped (typeof (IProductService), typeof (ProductService); // use ASP. NET Core comes with class services for dependency injection (DI) injection. addMvc ();} // This method gets called by the runtime. use this method to configure the HTTP request pipeline. public void Configure (IApplicationBuilder app, IHostingEnvironment env) {if (env. isDevelopment () {app. useDeveloperExceptionPage ();} app. useMvc ();}}}Configure the Mysql connection string in appsettings. json
{ "ConnectionStrings": { "MySqlConnection": "Server=localhost;database=NetCore_WebAPI-Mysql;uid=root;pwd=111111;" }, "Logging": { "IncludeScopes": false, "Debug": { "LogLevel": { "Default": "Warning" } }, "Console": { "LogLevel": { "Default": "Warning" } } }}Database migration:
Open the Package Manager Console: Tools> NuGet Package Manager> Package Manager Console. By default, the project selects the Assembly containing DbCOntext. Here is the DAL. Select all from the package source.
Input:
PM> add-migration init output "To undo this action, use Remove-Migration" To generate the migration code and then enter: PM> update-after the database is executed, the output "Done" indicates that the database has been updated successfully.
The complete procedure is as follows:
Tip: if this is not the first migration, you cannot enter PM> add-migration init, but enter:
PM> add-migration "description of this migration"
For example, the Name attribute is added to a table in Entity. during migration, enter PM> add-migration AddName.
After entering the preceding information to be executed, enter the following:
PM> update-database
The following directory is successfully generated in the DAL programmer
Then the database is opened, and the Product table is generated based on the Entity.
Run the program
If you Run the program successfully, you will be rewarded with a chicken leg crush.
Project download link: Demo
Github source code link:DotNetCore2.0