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

相关推荐
沐雨风栉2 分钟前
用 Kavita+cpolar 把数字书房装进口袋
服务器·开发语言·数据库·后端·golang
专注echarts研发20年26 分钟前
Qt自定义双击事件实现方案(规避原生双击附带单击问题)
数据库
Linux蓝魔28 分钟前
外网同步所有ubuntu源到内网使用
linux·数据库·ubuntu
墨香幽梦客33 分钟前
系统性能优化技巧:数据库索引、缓存与异步处理的综合应用
数据库·缓存·性能优化
meng半颗糖1 小时前
vue3+tpescript 点击按钮跳转新页面直接通过链接预览word
前端·vue.js·word
麦麦在写代码1 小时前
Mysql--DDL语句
数据库·mysql
击败不可能1 小时前
vue做任务工具方法的实现
前端·javascript·vue.js
觉醒大王1 小时前
医学好投的普刊分享
前端·论文阅读·深度学习·学习·自然语言处理·学习方法
小二·1 小时前
Python Web 开发进阶实战:AI 编排引擎 —— 在 Flask + Vue 中构建低代码机器学习工作流平台
前端·人工智能·python
【赫兹威客】浩哥1 小时前
【赫兹威客】框架模板-前端bat脚本部署教程
前端·vue.js