C#语言小白记录学习路程:
1.首先创建Furion文件,向.Core层导入包,包含:Furion包,Mysql.Data包,Sqlsugar包;
2.在.Core层创建 SqlsugarSetup.cs 文件:
//下列代码中,将 "db_master" 替换成 "DefaultConnection"
public static class SqlsugarSetup
{
public static void AddSqlsugarSetup(this IServiceCollection services, IConfiguration configuration, string dbName = "db_master")
{
//如果多个数数据库传 List<ConnectionConfig>
var configConnection=new ConnectionConfig()
{
DbType = SqlSugar.DbType.MySql,
ConnectionString = configuration.GetConnectionString(dbName),
IsAutoCloseConnection = true,
};
SqlSugarScope sqlSugar = new SqlSugarScope(configConnection,
db =>
{
//单例参数配置,所有上下文生效
db.Aop.OnLogExecuting = (sql, pars) =>
{
//Console.WriteLine(sql);//输出sql
};
});
services.AddSingleton<ISqlSugarClient>(sqlSugar);//这边是SqlSugarScope用AddSingleton
}
}
3. 在 Startup.cs 中注册 :
services.AddSqlsugarSetup(App.Configuration);
注: 可能需要使用 using 注入
4.在 appsetting.json 中替换数据库为:
"ConnectionStrings": {
"DefaultConnection": "server=10.10.10.240;Port=3306;uid=root;pwd=Dingli123456;database=exhibitionhall;sslmode=none;Charset=utf8mb4;",
"DbType": "MySql",
"IsAutoCloseConnection": "true"
}
5.实体类对象定义在.Core层中,建议在.Core层中创建文件夹,在文件夹中创建实体类;
注:1. 在创建实体类过程中,数据库中表的名称带有下划线,如:age_title ,但是在命名实体类时不能带有下划
线,应采用大驼峰命名法命名, 如: AgeTitle ,并且在对应的实体类前加上: [SugarTable("age_title")] ,
如果SugarTable 无法快捷引用,应使用using导入SqlSugar。
2. 在主键Id前面应加入 :[SugarColumn(IsPrimaryKey = true, IsIdentity = true)] 注明这是主键。
例:
[SugarTable("age_title")]
public class AgeTitle
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int Id { get; set; }
public int Age { get; set; }
public int Title { get; set; }
public int Number { get; set; }
}
6. 在 SystemService.cs 中 使用构造函数注入,
//1.构造函数注入
SqlSugar.ISqlSugarClient db;
public WeatherForecastController(ISqlSugarClient db)
{
this.db = db;
}
7. 在ISystemService.cs 中引用方法;
如:
public interface ISystemService
{
List<AgeTitle> GetAgeTitles();
int GetAgeCount();
}
8. 在 SystemAppService.cs 中引用函数:
如:
private readonly ISystemService _systemService;
public SystemAppService(ISystemService systemService)
{
_systemService = systemService;
}
public List<AgeTitle> GetAgeTitles()
{
return _systemService.GetAgeTitles();
}