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

相关推荐
阿星AI工作室1 小时前
一个简单Demo彻底理解前后端怎么连的丨Figma + Supabase + Vercel
前端·人工智能
Drifter_yh1 小时前
【黑马点评】Redisson 分布式锁核心原理剖析
java·数据库·redis·分布式·spring·缓存
鸽鸽程序猿1 小时前
【Redis】zset 类型介绍
数据库·redis·缓存
z玉无心1 小时前
Redis
数据库·redis·oracle
予枫的编程笔记1 小时前
【Redis核心原理篇2】Redis 单线程模型:为什么单线程还能这么快?
数据库·redis·缓存
aircrushin1 小时前
一拍即传的平替,完全免费的实时照片墙!
前端
fengxin_rou1 小时前
一文吃透 Redis 压缩列表、listpack 及哈希表扩容与并发查询
数据库·redis·散列表
一只鹿鹿鹿1 小时前
智慧水利一体化建设方案
大数据·运维·开发语言·数据库·物联网
_codemonster2 小时前
数据库字符集编码问题
android·数据库·oracle
鹏北海3 小时前
JSBridge 原理详解
前端