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

相关推荐
li星野几秒前
Function Call 完全指南:让大模型从“聊天”到“行动”
数据库·oracle
!chen2 分钟前
Oracle Deep Data Security (Deep Sec) 初体验
数据库·oracle·ffmpeg
IT_陈寒3 分钟前
Redis突然吃掉所有内存,我的服务差点挂了
前端·人工智能·后端
2601_958492553 分钟前
Behavioral Analysis of HTML5 Trivia Integration
前端·html·html5
淘矿人4 分钟前
Claude助力前端开发
java·数据库·git·python·sql·spring·database
weixin_444012936 分钟前
Go语言GORM怎么做分页_Go语言GORM分页查询教程【实用】
jvm·数据库·python
sakiko_10 分钟前
Swift/UIkit学习笔记27-模块管理,发送位置信息
前端·笔记·学习·ios·swift·uikit
hhb_61810 分钟前
Ruby核心技术难点梳理与实战应用案例解析
服务器·前端·ruby
天渺工作室19 分钟前
Vue自定义指令实现点击事件权限拦截控制的npm插件
前端·vue.js·npm
晓得迷路了21 分钟前
栗子前端技术周刊第 129 期 - TanStack npm 供应链入侵事件、pnpm 11.1、Tailwind CSS 4.3...
前端·javascript·css