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

相关推荐
合作小小程序员小小店几秒前
web网页开发,在线%医院诊断管理%系统,基于Idea,html,css,jQuery,java,jsp,ssh,mysql。
java·前端·css·数据库·jdk·html·intellij-idea
Alita11101_几秒前
深度测评:openGauss 在虚拟机中对 SQL92 标准的兼容性
数据库
w***954910 分钟前
【Redis】centos7 systemctl 启动 Redis 失败
数据库·redis·缓存
爱学习的程序媛11 分钟前
【Web前端】Vue2与Vue3核心概览与优化对比
前端·javascript·vue.js·typescript
li@h24 分钟前
如何在电脑端访问小程序时在胶囊添加一个全屏和缩放功能
前端
纪伊路上盛名在1 小时前
Alphafold实用指南—官网教程3
数据库·人工智能·机器学习·alphafold·计算生物学·结构生物学
Mr.wangh1 小时前
spring-cloud服务远程调用(Eureka、Nacos、OpenFeign)
数据库
LFly_ice1 小时前
学习React-23-React-router
前端·学习·react.js
a***97681 小时前
从MySQL迁移到PostgreSQL的完整指南
数据库·mysql·postgresql
c***72742 小时前
【Redis系列】RedisTemplate的使用与注意事项
数据库·redis·缓存