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 分钟前
【Redis】哨兵(Sentinel)机制
数据库·redis·sentinel
酷爱码4 分钟前
css中的 vertical-align与line-height作用详解
前端·css
悟能不能悟18 分钟前
mysql的not exists走索引吗
数据库·mysql
沐土Arvin18 分钟前
深入理解 requestIdleCallback:浏览器空闲时段的性能优化利器
开发语言·前端·javascript·设计模式·html
明月与玄武18 分钟前
Jmeter -- JDBC驱动连接数据库超详细指南
数据库·jmeter·配置jdbc连接
专注VB编程开发20年20 分钟前
VB.NET关于接口实现与简化设计的分析,封装其他类
java·前端·数据库
vvilkim25 分钟前
Redis持久化机制详解:保障数据安全的关键策略
数据库·redis·缓存
小妖66629 分钟前
css 中 content: “\e6d0“ 怎么变成图标的?
前端·css
cooldream200932 分钟前
信息安全的基石:深入理解五大核心安全服务
数据库·安全·系统架构师
大数据魔法师42 分钟前
Redis(三) - 使用Java操作Redis详解
java·数据库·redis