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

相关推荐
墨_风6 分钟前
MyBatis时间区间查询异常排查(达梦数据库)
数据库·mybatis·达梦
excel14 分钟前
JS 正则在多次 test() 时为什么会出现 lastIndex 缓存问题?
前端
IT_陈寒16 分钟前
为什么 Java 的 Optional 让我调试到深夜?
前端·人工智能·后端
njsgcs41 分钟前
用clip把设计经验变成向量数据库,然后每秒检索可以检查3维模型设计的错误吗
数据库
米丘1 小时前
React 19.x 的 lazy 与 Suspense
前端·javascript·react.js
如果超人不会飞1 小时前
TinyVue Grid 表格 fetchData 完全指南:从入门到精通
前端
WiChP1 小时前
【V0.1B10】从零开始的2D游戏引擎开发之路
java·数据库·游戏引擎
kyriewen1 小时前
手写虚拟DOM后,我反问面试官:key为什么不能用index?
前端·react.js·面试
小当家.1051 小时前
PostgreSQL 做向量数据库:pgvector 在 RAG 中的实战与多场景适配
数据库·人工智能·postgresql·rag
Doris_20231 小时前
说一说ESLint+Prettier生效的原理
前端·设计模式·架构