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

相关推荐
阿标在干嘛4 分钟前
分布式锁的“场景适配“:我们为什么在部分链路中选择了数据库乐观锁?
数据库·分布式
jiidd6 分钟前
关于SQL SERVICE数据库里换行问题
数据库·sql·oracle
夕阳_醉了9 分钟前
前端通用组件开发全指南|从 0 到 1 打造稳定可复用的业务组件
前端
java_nnnn9 分钟前
数据库读写分离与 Redis 缓存:从 MySQL 查询压力到缓存机制
数据库·redis·缓存
Amos_Web14 分钟前
Rspack 源码解析(三十):SourceMapDevToolPlugin 如何生成并关联 source map
前端
console.log('npc')19 分钟前
从0到1实现任务评价统计功能:React + TypeScript 实战指南(小白注释版)
前端·react.js·typescript
金仓社区的KK23 分钟前
数据库主备切换后,业务恢复了吗?五层验收清单
数据库·云计算·软件构建
zoyation25 分钟前
HBase 2.5.16 单机部署
大数据·数据库·hbase
l1t27 分钟前
DeepSeek总结的 PostgreSQL 中的二进制只读副本,第一部分
数据库·postgresql
java_prinln29 分钟前
9. Agent 的长短期记忆系统怎么做的?记忆是怎么存的?粒度是多少?怎么用的?
数据库·python·agent