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

相关推荐
TextIn智能文档云平台5 分钟前
图片转文字后怎么输入大模型处理
前端·人工智能·python
Java爱好狂.7 分钟前
Java面试Redis核心知识点整理!
java·数据库·redis·分布式锁·java面试·后端开发·java八股文
专注前端30年7 分钟前
在日常开发项目中Vue与React应该如何选择?
前端·vue.js·react.js
小程故事多_807 分钟前
开源界核弹级输出!蚂蚁 Agentar-Scale-SQL 凭 “编排式扩展” 技术,成为 Text-to-SQL 天花板
数据库·人工智能·sql·开源·aigc·embedding
文刀竹肃21 分钟前
DVWA -XSS(DOM)-通关教程-完结
前端·安全·网络安全·xss
lifejump24 分钟前
Pikachu | XSS
前端·xss
进击的野人28 分钟前
Vue 组件与原型链:VueComponent 与 Vue 的关系解析
前端·vue.js·面试
馬致远36 分钟前
Vue todoList案例 优化之本地存储
前端·javascript·vue.js
请叫我聪明鸭36 分钟前
CSS实现单行、多行文本超长显示 / 不超长隐藏、悬浮窗超长展示/不超长隐藏、悬浮窗手动控制样式
前端·javascript·css
blackorbird37 分钟前
苹果修复了两个在定向攻击中被利用的Webkit漏洞,其中一个与谷歌ANGLE漏洞同源
前端·webkit