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

相关推荐
2301_81564538几秒前
saas 一面
前端·面经
Leon-Ning Liu2 分钟前
【真实经验分享】Oracle 索引并行度引发的进程风暴分析与处理
数据库·oracle
大数据魔法师2 分钟前
MongoDB(十) - MongoDB分片集操作
数据库·mongodb
无风听海4 分钟前
OAuth 2.0 Scope 的使用与设计规划
前端
2501_916008897 分钟前
全面解析常用Web前端开发工具:编辑器、调试工具、性能分析器与框架
android·前端·ios·小程序·uni-app·编辑器·iphone
数据库知识分享者小北8 分钟前
AnalyticDB PostgreSQL 版软件 V2.0:安全可靠的全场景一站式数据仓库
数据库·postgresql·信创数据库·安全可靠数据库·analyticdb·阿里云 analyticdb
韦胖漫谈IT10 分钟前
B+ 树:为什么数据库索引偏爱它
数据库·oracle
暗夜猎手-大魔王10 分钟前
转载--Hermes Agent 08 | Agent 的自我进化:nudge、后台审查与轨迹数据
java·前端·人工智能
CIO4013 分钟前
IT故事(7): CIO之“10亿元库存数字化“
数据库
IT_陈寒19 分钟前
Redis集群节点迁移把我坑惨了,这个坑你得提前绕开
前端·人工智能·后端