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

相关推荐
kft13142 分钟前
XSS深度剖析:从弹窗到持久化窃取Cookie
前端·web安全·xss·安全测试
烬羽6 分钟前
《前端三权分立:HTML、CSS、JS为什么不能“乱搞”》
前端
恋爱脑11 分钟前
vue自定义指令封装-是否点击当前元素以外区域
前端
川冰ICE21 分钟前
TypeScript装饰器与元编程实战
前端·javascript·typescript
l1t29 分钟前
DeepSeek总结的在 DuckDB 中试驾 Lance 数据湖仓格式
数据库·人工智能·机器学习·duckdb
AI砖家33 分钟前
Vue3组件传参大全,各种传参方式的对比
前端·javascript·vue.js
希望永不加班33 分钟前
var局部变量类型推断的利弊
java·服务器·前端·javascript·html
PaperData40 分钟前
2017-2025年中国10米分辨率土地利用/覆盖栅格数据(from Esri LULC)
数据库·数据分析·学习方法
小二·42 分钟前
LangGraph 多智能体实战:从零搭建 Multi-Agent 协作系统
java·开发语言·数据库