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

相关推荐
Mh4 小时前
别再只会 `find` 了:Map 在前端业务里的真实用法
前端·javascript
陈随易5 小时前
FFmpeg 9.0 发布,代号 Lei,音视频处理再升级
前端·后端·程序员
爱丶狸5 小时前
Grafana_Zabbix_ImageRenderer_部署与前端操作手册
linux·前端·zabbix·grafana·kylin
凌虚8 小时前
面向 MySQL 用户的 PostgreSQL 快速上手指南
数据库·后端·架构
五阿哥永琪8 小时前
MySQL中操作json的函数!
数据库·mysql·json
用户059540174468 小时前
把AI对话记忆存储测试从手工改成Playwright+pytest,覆盖率从20%提到96%,回归时间缩短90%
前端·css
来者皆善8 小时前
了解Mysql优化吗?如何优化索引?
数据库·mysql
kyriewen8 小时前
别再这样写TypeScript了——Code Review中最常见的8个反模式
前端·javascript·typescript
名字还没想好☜9 小时前
Next.js ‘use client‘ 到底加在哪:Server/Client Components 边界与常见报错
开发语言·前端·javascript·react·next.js
午安~婉9 小时前
GitHub Token/ GitHub Stats统计显示图异常
前端·github·vercel·github token