h5个网站的区别,办公空间设计课程总结,深圳企业建站招聘,做网站需要公司资质吗用NetCore 和Dapper 和mySql做一个简单的实例#xff0c; 一准备工作 1#xff1a;VS2017windos系统#xff0c;也可以用其他的操作系统和工具 2#xff1a;一台Cenetos的虚拟机或者虚拟机 二#xff1a;开始 1#xff1a;用微软官方的netCore的ToDo项目改造#xff0c;…用NetCore 和Dapper 和mySql做一个简单的实例 一准备工作 1VS2017windos系统也可以用其他的操作系统和工具 2一台Cenetos的虚拟机或者虚拟机 二开始 1用微软官方的netCore的ToDo项目改造项目的主体结构如下图源连接 https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-web-api 1打开Nuget控制台安装 MySQL官方.NET Core驱动,并且支持 EF Core Install-Package SapientGuardian.MySql.Data -Pre 2打开Nuget控制台安装Dapper Install-Package Dapper -Pre 3在Models文件夹下新建ToDoItem 的实体 public class ToDoItem{[Required]public string ID { get; set; }[Required]public string Name { get; set; }[Required]public string Notes { get; set; }public bool Done { get; set; }}4在appsettings.json里面配置MySql的数据库连接字符串然后点开appsettings.json的属性将“复制到输出目录”项的值改为“始终复制” SslModenone的作用是解决连接的时候报SSL错误的 ConnectionStrings: {SqlServerConnection: Server(LocalDb)\\MSSQLLocalDB, Databasetest,MySqlConnection: Server自己的服务器;Databasetest;User IDroot;Password111111;SslModenone}5在Common下面新建一个AppConfigurtaionServices的类用于读取appsettings.json里面的连接字符串(appsettings.json属性如果没有选中始终复制在代码运行的时候 IConfiguration 会报错 ) public class AppConfigurtaionServices{public static IConfiguration Configuration { get; set; }static AppConfigurtaionServices(){Configuration new ConfigurationBuilder().Add(new JsonConfigurationSource { Path appsettings.json, ReloadOnChange true }).Build();}}6新建一个Interfaces文件夹然后下面建一个IToDoRepository的接口类 public interface IToDoRepository{bool DoesItemExist(string id);IEnumerableToDoItem All();ToDoItem Find(string id);int Insert(ToDoItem item);int Update(ToDoItem item);int Delete(string id);}7新建一个Services然后下面新建ToDoRepository类 是我们的数据仓储类 记得要引用(using Dapper;和 using MySql.Data.MySqlClient;) public class ToDoRepository : IToDoRepository{private static string DefaultSqlConnectionString ;public ToDoRepository(){DefaultSqlConnectionString AppConfigurtaionServices.Configuration.GetConnectionString(MySqlConnection); }public static IDbConnection GetSqlConnection(string sqlConnectionString null){if (string.IsNullOrWhiteSpace(sqlConnectionString)){sqlConnectionString DefaultSqlConnectionString;}IDbConnection conn new MySqlConnection(sqlConnectionString);conn.Open();return conn;}/// summary/// 获取全部/// /summary/// returns/returnspublic IEnumerableToDoItem All(){using (IDbConnection conn GetSqlConnection()){string strsql select * from ToDoItem;return conn.QueryToDoItem(strsql, null);}}/// summary/// 查询是否存在/// /summary/// param nameid/param/// returns/returnspublic bool DoesItemExist(string id){using (IDbConnection conn GetSqlConnection()){int cout conn.Queryint(select count(*) from ToDoItem where IDID, new { ID id }).FirstOrDefault();if (cout 0)return true;elsereturn false;}}/// summary/// 删除/// /summary/// param nameid/param/// returns/returnspublic int Delete(string id){using (IDbConnection conn GetSqlConnection()){string strsql DELETE from ToDoItem where IDID;return conn.Execute(strsql, new { ID id });}}/// summary/// 查询整个对象/// /summary/// param nameid/param/// returns/returnspublic ToDoItem Find(string id){using (IDbConnection conn GetSqlConnection()){string strsql select * from ToDoItem where IDID;return conn.QueryToDoItem(strsql, new { ID id }).FirstOrDefault();}}/// summary/// 新增项/// /summary/// param nameitem/param/// returns/returnspublic int Insert(ToDoItem item){using (IDbConnection conn GetSqlConnection()){string strsql INSERT into ToDoItem(ID,Name,Notes,Done)values(ID,Name,Notes,Done);return conn.Execute(strsql, item);}}/// summary/// 修改/// /summary/// param nameitem/param/// returns/returnspublic int Update(ToDoItem item){using (IDbConnection conn GetSqlConnection()){string strsql UPDATE ToDoItem SET NameName,NotesNotes,DoneDone where IDID;return conn.Execute(strsql, item);}}}8在Controller下面新增一个ToDoItemsController的控制器记得添加相关的命名空间 [Route(api/[controller])]public class ToDoItemsController : Controller{private readonly IToDoRepository _toDoRepository;public ToDoItemsController(IToDoRepository toDoRepository){_toDoRepository toDoRepository;}/// summary/// 获取数据/// /summary/// returns/returns[HttpGet]public IActionResult List(){return Ok(_toDoRepository.All());}/// summary/// 新增项/// /summary/// param nameitem/param/// returns/returns[HttpPost]public IActionResult Create([FromBody] ToDoItem item){try{if (item null || !ModelState.IsValid){return BadRequest(没有通过验证);}bool itemExists _toDoRepository.DoesItemExist(item.ID);if (itemExists){return StatusCode(StatusCodes.Status409Conflict, 已经存在此项);}_toDoRepository.Insert(item);}catch (Exception){return BadRequest(创建失败);}return Ok(item);}/// summary/// 修改项/// /summary/// param nameitem/param/// returns/returns[HttpPut]public IActionResult Edit([FromBody] ToDoItem item){try{if(itemnull || !ModelState.IsValid)return BadRequest(没有通过必填验证);var existingItem _toDoRepository.Find(item.ID);if(existingItemnull){return NotFound(没有发现此记录);}_toDoRepository.Update(item);}catch(Exception){return BadRequest(修改失败);}return NoContent();}/// summary/// 删除/// /summary/// param nameid/param/// returns/returns[HttpDelete({id})]public IActionResult Delete(string id){try{var item _toDoRepository.Find(id);if (item null)return NotFound(没有此记录);_toDoRepository.Delete(id);}catch(Exception ){return BadRequest(删除失败);}return NoContent();}}9在ConfigureServices里配置IToDoRepository 和ToDoRepository服务 services.AddSingletonIToDoRepository, Services.ToDoRepository();10配置Swagger(丝袜哥)具体Swagger的基础知识可以连接到 https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/web-api-help-pages-using-swagger?tabsvisual-studio10.1在Nuget控制台添加引用 Install-Package Swashbuckle.AspNetCore 10.2:在Startup类中配置Swagger 10.2.1在ConfigureServices方法里面添加Swagger服务 //添加Swagger服务services.AddSwaggerGen(c {c.SwaggerDoc(v1, new Info{Version v1,Title ToDo API,Description A simple example ASP.NET Core Web API,TermsOfService None,Contact new Contact { Name Shayne Boyer, Email , Url https://twitter.com/spboyer },License new License { Name Use under LICX, Url https://example.com/license }});var basePath PlatformServices.Default.Application.ApplicationBasePath;var xmlPath Path.Combine(basePath, ToDoApi.xml);c.IncludeXmlComments(xmlPath);});10.2.2在Configure配置Swagger服务 app.UseSwagger();
//配置Swagger服务
app.UseSwaggerUI(c
{c.SwaggerEndpoint(/swagger/v1/swagger.json, My API V1);
});10.3最终的Startup类如下 using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.PlatformAbstractions;
using Swashbuckle.AspNetCore.Swagger;
using System.IO;
using ToDoApi.Interfaces;namespace ToDoApi
{public class Startup{public Startup(IConfiguration configuration){Configuration configuration;}public IConfiguration Configuration { get; }//添加服务public void ConfigureServices(IServiceCollection services){services.AddMvc();//添加Swagger服务services.AddSwaggerGen(c {c.SwaggerDoc(v1, new Info{Version v1,Title ToDo API,Description A simple example ASP.NET Core Web API,TermsOfService None,Contact new Contact { Name Shayne Boyer, Email , Url https://twitter.com/spboyer },License new License { Name Use under LICX, Url https://example.com/license }});var basePath PlatformServices.Default.Application.ApplicationBasePath;var xmlPath Path.Combine(basePath, ToDoApi.xml);c.IncludeXmlComments(xmlPath);});services.AddSingletonIToDoRepository, Services.ToDoRepository();}// 配置服务public void Configure(IApplicationBuilder app, IHostingEnvironment env){app.UseSwagger();//配置Swagger服务app.UseSwaggerUI(c {c.SwaggerEndpoint(/swagger/v1/swagger.json, My API V1);});//配置开发环境if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}app.UseMvc();}}
}10.4启动项设置为swagger启动 在launchSettings.json做如下修改 这样你的项目用IIS Express启动来就是swagger界面 11最终效果 11.2测试获取数据的方法 12:对NetCore的理解还很浅只是做了一个简单的demo希望能帮到你只是写了mysql的如果是要用SqlServer,则修改读取SqlServerConnection的数据连接然后把数据仓储里面的 MySql.Data.MySqlClien改成Sql server的就可以了 13demo连接 https://files.cnblogs.com/files/gouguo/ToDoApi.rar转载于:https://www.cnblogs.com/gouguo/p/8961516.html