数据库用户(User)和模式(Schema)
为确保FreeSql正确访问数据库,项目中使用的用户名与模式名应一致
连接字符串(ConnectionString)
FreeSql的达梦连接格式如:
"Server=192.168.2.14:5236;User Id=SA;PWD=123$Oops;DATABASE=TestDB;poolsize=5"
注意:此处的DATABASE是你在达梦管理工具中新建实例时设定的数据库名
appsettings.json示例:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DMv8": "Server=192.168.2.14:5236;User Id=SA;PWD=123$Oops;DATABASE=TestDB;poolsize=5"
}
}
依赖注入
Program.cs片段:
...
var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;
var fsql = new FreeSqlBuilder()
.UseConnectionString(DataType.Dameng, configuration.GetConnectionString("DMv8"))
.UseAutoSyncStructure(true)
.Build();
builder.Services.AddControllers();
...
builder.Services.AddSingleton(fsql);
在控制器中调用
注:由于DbContext 不是线程安全的,本例取自某注重高并发的现有项目国产化迁移故而未采用,如需采用DbContext具体见FreeSql相关说明
public class TestController(IFreeSql fsql) : ControllerBase
{
private readonly IFreeSql _fsql = fsql;
[HttpGet]
[Route("QueryTest/{deptno}")]
public ActionResult<ApiResult> QueryTest(string deptno)
{
var query = _fsql.Select<TestTable>().Where(r => r.DPT == Convert.ToInt32(deptno.Trim()) && r.Status == 0).ToList();
...
...
}
}