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

相关推荐
夜雪一千6 分钟前
标题特殊符号数据清洗实战:解决HTML实体、零宽字符、Emoji乱码踩坑
前端·html
❀͜͡傀儡师10 分钟前
MySQL REST Service 认证鉴权体系与 MySQL 26.10.0 内置化演进
数据库·mysql·adb
wifi___14 分钟前
Redis分布式锁
数据库·redis·分布式
richdata17 分钟前
从采购承诺到库存周转:降低库存资金占用的六个计划杠杆
大数据·前端·javascript
4SAPI29 分钟前
营销内容生成大模型 API 生产选型指南:4SAPI、硅基流动与 OpenRouter 的架构权衡
数据库·人工智能·架构·php
zyxqyy&∞31 分钟前
sqli-labs-union联合查询(Less1-Less4)
数据库·安全
数据库小学妹39 分钟前
MySQL binlog格式怎么选?ROW、STATEMENT、MIXED的区别与坑
数据库·mysql·binlog·主从复制·数据一致性
计算机魔术师42 分钟前
别人IPO发股票,Anthropic一口气搞出五类
前端
小冯不疯1 小时前
查询旺店通货品策略实战教程:从源系统拉取到轻易云的端到端落地
java·大数据·数据库
ai_coder_ai1 小时前
使用Web IDE边写自动化脚本
运维·前端·自动化