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

相关推荐
雪隐7 小时前
用Flutter做背单词APP-01服务器?不存在的,我家里就有
前端·人工智能·后端
用户2204603958688 小时前
ES模块和commonJS两种标准下中实现__dirname?一篇文章教你理清楚
前端
Database_Cool_8 小时前
单库瓶颈解决方案首选:阿里云 PolarDB-X 平滑替代分库分表
数据库·阿里云
2503_931712488 小时前
10m/s超高速电梯:西奥XO-NEWIII如何树立行业速度标杆
java·大数据·数据库
无小道8 小时前
Redis——redis和mysql的数据同步
数据库·redis·mysql
犹豫的大炮8 小时前
jQuery最核心的基础设施之一——数据缓存模块进化史
前端·缓存·jquery
小碗细面8 小时前
从 PRD 到上线:SpecKit 如何让 AI 真正参与前端交付
前端·ai编程·claude
AI的探索之旅8 小时前
从 Ubuntu 14.04 到 24.04:TI AM335x 开发环境完整迁移与 Agent 接管方案
linux·数据库·嵌入式硬件·ubuntu·postgresql
WL学习笔记9 小时前
链式队列(数据结构)
前端·数据结构·jquery
我是大卫9 小时前
React源码解析-第三部分:协调与提交
前端·react.js·源码