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 = configuration[dbName],

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、运行效果

相关推荐
索西引擎1 分钟前
【实战】Changesets:Monorepo 版本管理与变更日志的实践
前端
AC赳赳老秦13 分钟前
OpenClaw与思维导图工具联动:自动生成工作规划脑图、拆解任务节点,适配职场管理
java·大数据·服务器·数据库·python·php·openclaw
大熊程序猿14 分钟前
ASP.NET Core 认证授权:JWT与OAuth2实战
后端·asp.net
Highcharts.js15 分钟前
AI向量知识谱系图表创建示例代码|Highcharts网络图表(networkgraph)搭建案例
开发语言·前端·javascript·网络·信息可视化·编辑器·highcharts
zhangxingchao32 分钟前
AI应用开发五:RAG高级技术与调优
前端·人工智能·后端
zhishijike33 分钟前
全国行政区划sql(省市区)
数据库·sql·mysql
KaMeidebaby43 分钟前
卡梅德生物技术快报|单 B 细胞抗体技术:全犬源单抗制备流程、关键参数与性能验证
前端·数据库·其他·百度·新浪微博
KG_LLM图谱增强大模型1 小时前
scHilda:大模型与知识图谱分层融合,突破单细胞分型瓶颈
数据库·人工智能·知识图谱
凯瑟琳.奥古斯特1 小时前
力扣3654:二维矩阵连续空位统计
数据结构·数据库·算法·职场和发展
hazel1 小时前
网络与工程化
前端