ASP.NET WEB API通过SugarSql连接MySQL数据库

注意:VS2022企业版可以,社区版可能存在问题。实体名称和字段和数据库中的要一致。

1、创建项目,安装SqlSugarCore、Pomelo.EntityFrameworkCore.MySql插件

2、文件结构

2、appsettings.json

{

"Logging": {

"LogLevel": {

"Default": "Information",

"Microsoft.AspNetCore": "Warning"

}

},

"AllowedHosts": "*",

"ConnectionString": "Server=127.0.0.1;port=3306;database=blog_db;uid=root;pwd=123456;"

}

3、SqlSugarSetup.cs

using SqlSugar;

namespace MySqlApp.Db

{

public static class SqlSugarSetup

{

public static void AddSqlSugarSetup(this IServiceCollection services, IConfiguration configuration, string dbName= "ConnectionString")

{

SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()

{

DbType = SqlSugar.DbType.MySql,

ConnectionString = configurationdbName,

IsAutoCloseConnection = true,

},

db =>

{

db.Aop.OnLogExecuting = (sql, pars) =>

{

Console.WriteLine(sql);

};

});

services.AddSingleton(sqlSugar);

}

}

}

4、Program.cs

builder.Services.AddSqlSugarSetup(builder.Configuration);

5、blog_type.cs

namespace MySqlApp.Model

{

public class blog_type

{

public int type_id { get; set; }

public string type_name { get; set; } = string.Empty;

}

}

6、BlogTypeController.cs

using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc;

using MySqlApp.Model;

using SqlSugar;

namespace MySqlApp.Controllers

{

Route("api/\[controller\]")

ApiController

public class BlogTypeController : ControllerBase

{

private readonly ISqlSugarClient _db;

public BlogTypeController(ISqlSugarClient db) {

_db = db;

}

HttpGet

public IActionResult Get()

{

var a = _db.Queryable<blog_type>().ToList();

return Ok(a);

}

}

}

7、运行效果

相关推荐
shadow_glory2 分钟前
vue3自定义指令directives
前端·javascript·vue.js
Front思2 分钟前
如何学习Shopify前端开发?
前端·学习
mN9B2uk173 分钟前
数据库设计 Step by Step
数据库·oracle·数据库开发
码云骑士4 分钟前
语音合成演示 - Web Speech API
前端
ZC跨境爬虫5 分钟前
跟着 MDN 学CSS day_50:(传统布局方法与网格系统)
前端·css·ui·tensorflow·媒体
abcy0712135 分钟前
oracle配置pdb账号密码图文教程
数据库·oracle
薛先生_0998 分钟前
vue-路由模块封装
前端·javascript·vue.js
这个DBA有点耶9 分钟前
当时间数据不再只是“曲线”:聊聊时序数据库和融合分析
数据库·sql·程序人生·云原生·运维开发·时序数据库·业界资讯
薛先生_0999 分钟前
vue-router-link实现导航高亮效果
前端·javascript·vue.js
郑州光合科技余经理10 分钟前
海外版外卖系统源码:支付/地图/多语言核心代码实现
android·java·前端·后端·架构·uni-app·php