简易FreeSql分表查、增、删、改操作例子
参考:
1.FreeSql官方文档
2.FreeSql分表分库
1.创建连接
private readonly IFreeSql _freeSql;
public FreeSqlService(IConfiguration configuration)
{
var _configuration = configuration["ConnectionStrings:Default"];
_freeSql = new FreeSql.FreeSqlBuilder().UseConnectionString(FreeSql.DataType.MySql, _configuration).Build();
}
2.创建各方法
说明
我这里分表是根据时间来分
这里参数根据实际情况来创建,我这里是为了方便 用于拼接分表的表名
一般来说是要根据传入的时间来判定所需要查询的分表范围,而不是直接传入分表时间参数。。。
/// <summary>
/// 分表查询
/// </summary>
/// <param name="yearmonth">表年月</param>
/// <returns></returns>
public List<DataForecastModel> Get(List<string> yearmonth)
{
ISelect<DataForecastModel> data = _freeSql.Select<DataForecastModel>();
foreach (var item in yearmonth)
{
data.AsTable((type, x) => $"{x}_{item}");
}
return data.ToList();
}
/// <summary>
/// 批量分表插入数据
/// </summary>
/// <param name="datas"></param>
/// <param name="yearmonth"></param>
/// <returns></returns>
public bool Insert(List<DataForecastModel> datas,string yearmonth)
{
try
{
var items = new List<DataForecastModel>();
foreach (var item in datas)
{
items.Add(new DataForecastModel
{
Time = item.Time,
Weather = item.Weather
});
}
var res = _freeSql.Insert(items).AsTable((x) => $"{x}_{yearmonth}").ExecuteAffrows();
return res > 0 ? true : false;
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 批量分表更新数据
/// </summary>
/// <param name="datas"></param>
/// <param name="yearmonth"></param>
/// <returns></returns>
public bool Update(List<DataForecastModel> datas, string yearmonth)
{
try
{
var res = _freeSql.Update<DataForecastModel>().SetSource(datas).AsTable((x) => $"{x}_{yearmonth}").ExecuteAffrows();
return res > 0 ? true : false;
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 批量分表删除数据
/// </summary>
/// <param name="Id"></param>
/// <param name="yearmonth"></param>
/// <returns></returns>
public bool Delete(List<string> Id, string yearmonth)
{
try
{
var res = _freeSql.Delete<DataForecastModel>(Id).AsTable((x) => $"{x}_{yearmonth}").ExecuteAffrows();
return res > 0 ? true : false;
}
catch (Exception ex)
{
return false;
}
}
3.调用
依赖注入后调用即可
private readonly IFreeSqlService _freeSqlService;
public WeatherForecastController(IFreeSqlService freeSqlService)
{
_freeSqlService = freeSqlService;
}
[HttpPost("DataPost")]
public List<DataForecastModel> DataPost(List<string> yearmonth)
{
var data = _freeSqlService.Get(yearmonth);
return data;
}
[HttpPost("PostInsert")]
public bool PostInsert(string yearmonth)
{
var datas = _freeSqlService.Get(new List<string> { yearmonth });
var res = _freeSqlService.Insert(datas,yearmonth);
return res;
}
[HttpPost("PostUpdate")]
public bool PostUpdate(List<DataForecastModel> data, string yearmonth)
{
var res = _freeSqlService.Update(data, yearmonth);
return res;
}
[HttpPost("PostDelete")]
public bool PostDelete(List<string> id, string yearmonth)
{
var res = _freeSqlService.Delete(id, yearmonth);
return res;
}
4.例子
数据库
参数:[“202204”,“202205”]