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

相关推荐
半岛@少年2 分钟前
Webpack在前端项目中究竟发挥什么作用?
前端·webpack·前端工程化
2501_940041744 分钟前
企业官网与品牌落地页,能直接交付的前端题目
前端
程序猿乐锅5 分钟前
【MySQL | 第七篇】 索引使用规则
数据库·sql·mysql
小番茄夫斯基11 分钟前
全球大模型的价格和能力排行汇总
前端·后端·架构
C137的本贾尼13 分钟前
崩溃恢复揭秘:从 Redo Log 到数据一致性
数据库
Lyyaoo.14 分钟前
【MySQL】锁机制
android·数据库·mysql
文中金域19 分钟前
备份sqlite数据库
数据库·sqlite
摇滚侠22 分钟前
Maven 入门+高深 SSM 案例 111-112
java·数据库·maven
小小小小宇24 分钟前
前端领域 30 个值得安装的 Agent Skills
前端
喵了几个咪28 分钟前
基于 Next.js 的 Headless CMS 前端架构:技术解析与二次开发导引
前端·javascript·架构