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

相关推荐
Mike117.3 小时前
GBase 8a 日期边界写法和时间窗口取数偏差
数据库
余人于RenYu3 小时前
Claude + Figma MCP
前端·ui·ai·figma
SPC的存折4 小时前
1、Redis数据库基础
linux·运维·服务器·数据库·redis·缓存
杨艺韬6 小时前
vite内核解析-第2章 架构总览
前端·vite
我是伪码农6 小时前
外卖餐具智能推荐
linux·服务器·前端
2401_885885047 小时前
营销推广短信接口集成:结合营销策略实现的API接口动态变量填充方案
前端·python
小李子呢02117 小时前
前端八股性能优化(2)---回流(重排)和重绘
前端·javascript
程序员buddha7 小时前
深入理解ES6 Promise
前端·ecmascript·es6
吴声子夜歌7 小时前
ES6——Module详解
前端·ecmascript·es6
MatrixOrigin8 小时前
数据库没有死,只是范式变了
数据库·oracle