netcore3.1API+efcore快速搭建
框架結構#
實體層 Aer.Enties#
Models-->實體類
業務層 After.IService#
IAltestitemController.cs
業務層 After.Service#
AlltestitemService.cs
接口層 AfterCore#
Controllers-> AlltestitemController.cs
一 EF從數據庫生成實體類到Enties#
1.執行以下語句安裝依賴包#
Install-Package MySql.Data.EntityFrameworkCore -Pre
Install-Package Pomelo.EntityFrameworkCore.MySql
Install-Package Microsoft.EntityFrameworkCore.Tools
Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design
2.在程序包包管理器控制台#
Scaffold-DbContext "server=localhost;userid=root;pwd=1;port=3306;database=syerp;sslmode=none;" Pomelo.EntityFrameworkCore.MySql -OutputDir Models -Force
二 業務層#
添加IAlltestitemService.cs接口
using AfterCore.Models; using System.Collections.Generic; using System.Threading.Tasks; namespace After.IService { public interface IAlltestitemService { /// <summary> /// 查詢所有 /// </summary> /// <returns></returns> Task<List<Alltestitem>> GetAllAsync(); /// <summary> /// 查詢總數 /// </summary> /// <returns></returns> Task<int> CountAsync(); } }
After.Service接口實現
AlltestitemService.cs
using After.IService; using AfterCore.Models; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Threading.Tasks; namespace After.Service { public class AlltestitemService : IAlltestitemService { private readonly testContext _testDbContext;//DB public AlltestitemService(testContext testContexts) { _testDbContext = testContexts; } public async Task<int> CountAsync() { return await _testDbContext.Alltestitem.CountAsync(); } public async Task<List<Alltestitem>> GetAllAsync() { return await _testDbContext.Alltestitem.ToListAsync(); } } }
三 注冊DbContext#
appsettings.json#
"ConnectionStrings": { "DefaultConnection": "Server=;database=test;uid=root;pwd=m;" },
Startup.cs#
//注冊DbContext ConfigureServices services.AddDbContext<testContext>(options => options.UseMySql(Configuration.GetConnectionString("DefaultConnection"))); services.AddControllers(); services.AddScoped<IAlltestitemService, AlltestitemService>();//ioc
四 添加Swagger#
安裝依賴包#
Swashbuckle.AspNetCore
ConfigureServices(IServiceCollection services)#
//注冊swagger服務 services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "SN博客 API", Description = "EFCore數據操作 ASP.NET Core Web API", TermsOfService = new Uri("https://example.com/terms"), Contact = new OpenApiContact { Name = "Shayne Boyer", Email = string.Empty, Url = new Uri("https://twitter.com/spboyer"), }, License = new OpenApiLicense { Name = "Use under LICX", Url = new Uri("https://example.com/license"), } }); // 為 Swagger 設置xml文檔注釋路徑 var basePath2 = AppContext.BaseDirectory;// xml路徑 //var xmlModelPath = Path.Combine(basePath2, "Snblog.Enties.xml");//Model層的xml文件名 var corePath = Path.Combine(basePath2, "AfterCore.xml");//API層的xml文件名 //c.IncludeXmlComments(xmlModelPath); c.IncludeXmlComments(corePath, true); //添加對控制器的標簽(描述) c.CustomSchemaIds(type => type.FullName);// 可以解決相同類名會報錯的問題 // c.OperationFilter<AddResponseHeadersFilter>(); // c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>(); // // c.OperationFilter<SecurityRequirementsOperationFilter>(); });
Configure(IApplicationBuilder app, IWebHostEnvironment env)#
#region Swagger //可以將Swagger的UI頁面配置在Configure的開發環境之中 app.UseSwagger(); //和Swagger UI app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "SN博客API"); c.RoutePrefix = string.Empty; }); #endregion
五 顯示層AfterCore#
Controllers->AlltestitemController.cs
using After.IService; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; //默認的約定集將應用於程序集中的所有操作: [assembly: ApiConventionType(typeof(DefaultApiConventions))] namespace AfterCore.Controllers { [Route("api/[controller]")] [ApiController] public class AlltestitemController : ControllerBase { private readonly IAlltestitemService _service; //IOC依賴注入 public AlltestitemController(IAlltestitemService service) { _service = service; } /// <summary> /// 查詢所有 /// </summary> /// <returns></returns> // [ApiExplorerSettings(IgnoreApi = true)] //隱藏接口 或者直接對這個方法 private,也可以直接使用obsolete屬性 [HttpGet("GetAllAsync")] public async Task<IActionResult> GetAllAsync() { return Ok(await _service.GetAllAsync()); } /// <summary> /// 查詢總數 /// </summary> /// <returns></returns> // [ApiExplorerSettings(IgnoreApi = true)] //隱藏接口 或者直接對這個方法 private,也可以直接使用obsolete屬性 [HttpGet("CountAsync")] public async Task<IActionResult> CountAsync() { return Ok(await _service.CountAsync()); } } }