当前位置:网站首页>DotNet圈里一个优秀的ORM——FreeSql
DotNet圈里一个优秀的ORM——FreeSql
2022-07-02 23:09:00 【InfoQ】
前言
推荐理由
应用案例
注入服务
public void ConfigureServices(IServiceCollection services)
{
//日志初始化
services.ConfigureLog();
// orm框架
services.ConfigureOrm(Configuration);
// 缓存配置
services.ConfigureRedis(Configuration);
// 登录授权,跨域策略,session配置
services.ConfigurePolicy(Configuration);
//mvc配置
services.ConfigureMvc(Configuration);
//其他插件配置
services.ConfigurePlug(Configuration);
}static IdleBus<IFreeSql> ib = new IdleBus<IFreeSql>(TimeSpan.FromMinutes(10));
public static void ConfigureOrm(this IServiceCollection services, IConfiguration configuration)
{
#region orm框架
ib.Register("db_system", () => new FreeSqlBuilder().UseConnectionString(DataType.SqlServer, configuration.GetConnectionString("CysccSystemConnString")).Build());
ib.Register("db_castic", () => new FreeSqlBuilder().UseConnectionString(DataType.SqlServer, configuration.GetConnectionString("CysccCasticConnString")).Build());
ib.Register("db_robot", () => new FreeSqlBuilder().UseConnectionString(DataType.SqlServer, configuration.GetConnectionString("CysccRobotConnString")).Build());
ib.Register("db_passport", () => new FreeSqlBuilder().UseConnectionString(DataType.SqlServer, configuration.GetConnectionString("PassportConnString")).Build());
ib.Register("db_matchai", () => new FreeSqlBuilder().UseConnectionString(DataType.SqlServer, configuration.GetConnectionString("MatchAIConnString")).Build());
ib.Register("db_checkin", () => new FreeSqlBuilder().UseConnectionString(DataType.SqlServer, configuration.GetConnectionString("CheckInConnString")).Build());
services.AddSingleton(ib);
#endregion
}生成模型对象

编写基本操作方法和接口
public class MatchAiRespository<T>: IMatchAiRespository<T> where T : class
{
public class MatchAiRespository<T>: IMatchAiRespository<T> where T : class
{
IdleBus<IFreeSql> fsql = null;
const string conn_str = "db_matchai";
public MatchAiRespository(IdleBus<IFreeSql> fsql)
{
this.fsql = fsql;
}
/// <summary>
/// 分页检索,并返回总数
/// </summary>
/// <param name="predicate"></param>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="total"></param>
/// <returns></returns>
public List<T> getList(Expression<Func<T, bool>> predicate, int pageIndex, int pageSize, out long total)
{
return fsql.Get(conn_str).Select<T>().Where(predicate).Count(out total).Page(pageIndex, pageSize).ToList();
}
/// <summary>
/// 获取记录数
/// </summary>
/// <param name="predicate"></param>
/// <returns></returns>
public async Task<long> getCountAsync(Expression<Func<T, bool>> predicate)
{
return await fsql.Get(conn_str).Select<T>().Where(predicate).CountAsync();
}
/// <summary>
/// 新增单条条目,返回影响条数
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public int addItem(T t)
{
return fsql.Get(conn_str).Insert<T>(t).ExecuteAffrows();
}
...
}
}public interface IMatchAiRespository<T> where T:class
{
/// <summary>
/// 分页检索,并返回总数
/// </summary>
/// <param name="predicate"></param>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="total"></param>
/// <returns></returns>
List<T> getList(Expression<Func<T, bool>> predicate, int pageIndex, int pageSize, out long total);
/// <summary>
/// 获取记录数(异步)
/// </summary>
/// <param name="predicate"></param>
/// <returns></returns>
Task<long> getCountAsync(Expression<Func<T, bool>> predicate);
/// <summary>
/// 新增单条条目,返回影响条数
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
int addItem(T t);
...
}public class CertRecordRepo : MatchAiRespository<Cert_Template>, Interfaces.ICertTemplateRespo
{
private IdleBus<IFreeSql> fsql;
const string conn_str = "db_matchai";
public CertRecordRepo(IdleBus<IFreeSql> fsql) : base(fsql)
{
this.fsql = fsql;
}
/// <summary>
/// 获取证书发放记录
/// </summary>
/// <param name="whereJsonStr"></param>
/// <param name="total"></param>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <returns></returns>
public dynamic GetCertRecords(string whereJsonStr, out long total, int pageIndex = 1, int pageSize = 10)
{
DynamicFilterInfo dyfilter = JsonConvert.DeserializeObject<DynamicFilterInfo>(whereJsonStr);
return fsql.Get(conn_str).Select<Cert_Record>()
.WhereDynamicFilter(dyfilter)
.Count(out total)
.Page(pageIndex, pageSize)
.ToList();
}
/// <summary>
/// 获取证书导出记录(选拔赛赛)
/// </summary>
/// <param name="whereJsonStr"></param>
/// <returns></returns>
public async Task<List<CostumModels.CertRecordModel>> GetCertRecordsForExcel(string whereJsonStr)
{
DynamicFilterInfo dyfilter = JsonConvert.DeserializeObject<DynamicFilterInfo>(whereJsonStr);
var list = await fsql.Get(conn_str).Select<Cert_Record, Cert_Template, VIW_ScratchProgramApplyMain>()
.LeftJoin((a, b, c) => a.Template_id == b.TemplateID)
.LeftJoin((a, b, c) => a.ProjectNo == c.ProjectNo)
.WhereDynamicFilter(dyfilter)
.ToListAsync((a, b, c) => new CostumModels.CertRecordModel
{
CertContent = a.CertContent,
ProgramTypeCaption = c.ProgramTypeCaption,
ProjectNo = a.ProjectNo,
ProgramTypeCaptionParent = c.ProgramTypeCaptionParent,
ProjectSortCaption = c.ProjectSortCaption,
ProjectWorkCaption = c.ProjectWorkCaption,
TeamCaption = c.TeamCaption,
TemplateTypeCaption = b.TemplateTypeCaption,
ProjectTitle = c.ProjectTitle,
Score = c.Score,
//HasScore = c.HasScored,
AwardName = a.AwardName,
ProvinceShortName = c.ProvinceShortName,
CertType = a.CertType,
CertNo = a.CertNum
});
return list;
}
}控制器
[Area("space")]
[Authorize]
public class CertController : Controller
{
private readonly ICertRecordRepo certRepo;
private readonly INpoiExcelOperationService npoi;
private readonly IWebHostEnvironment en;
private readonly IResponseHelper resp;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="certRepo"></param>
/// <param name="resp"></param>
/// <param name="en"></param>
/// <param name="npoi"></param>
public CertController( ICertRecordRepo certRepo,IResponseHelper resp,IWebHostEnvironment en, INpoiExcelOperationService npoi)
{
this.certRepo = certRepo;
this.en = en;
this.resp = resp;
this.npoi = npoi;
}
/// <summary>
/// 获取颁发记录
/// </summary>
/// <param name="whereJsonstr"></param>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <returns></returns>
[ResponseCache(Duration =100,VaryByQueryKeys = new string[] {"whereJsonstr","rid"})]
public IActionResult GetCertRecords(string whereJsonstr, int pageIndex = 1, int pageSize = 10)
{
long total = 0;
return Json(_resp.success(new { items = _recordRepo.GetCertRecords(whereJsonstr, out total, pageIndex, pageSize), total }));
}
/// <summary>
/// 导出表格
/// </summary>
/// <param name="npoi"></param>
/// <param name="whereJsonstr"></param>
/// <returns></returns>
[HttpPost,ValidateAntiForgeryToken]
public async Task<IActionResult> ExportCertRecords([FromServices] INpoiExcelOperationService npoi, string whereJsonstr)
{
var list = await _recordRepo.GetCertRecordsForExcel(whereJsonstr);
return Json(await npoi.ExcelDataExportTemplate($"赛项【{list.First().ProgramTypeCaption}】证书发放记录", list.First().ProgramTypeCaption, list, _en.WebRootPath));
}
}


边栏推荐
- What are the recommended thesis translation software?
- Returns the maximum distance between two nodes of a binary tree
- Open Source | Wenxin Big Model Ernie Tiny Lightweight Technology, Accurate and Fast, full Open Effect
- Bigder:32/100 测试发现的bug开发认为不是bug怎么处理
- Unique line of "Gelu"
- Slf4j + logback logging framework
- Define MySQL function to realize multi module call
- Basic 10 of C language: array and pointer
- Which websites can I search for references when writing a thesis?
- 35 pages dangerous chemicals safety management platform solution 2022 Edition
猜你喜欢

Pytorch里面多任务Loss是加起来还是分别backward?

Maya fishing house modeling

Realization of mask recognition based on OpenCV

Where can I find the English literature of the thesis (except HowNet)?

pageoffice-之bug修改之旅

Interpretation of new plug-ins | how to enhance authentication capability with forward auth

Interface difference test - diffy tool

TypeError: Cannot read properties of undefined (reading ***)

Install docker and use docker to install MySQL
![MATLAB signal processing [Q & a notes-1]](/img/53/ae081820fe81ce28e1f04914678a6f.png)
MATLAB signal processing [Q & a notes-1]
随机推荐
The privatization deployment of SaaS services is the most efficient | cloud efficiency engineer points north
Monitor container runtime tool Falco
在线预览Word文档
The privatization deployment of SaaS services is the most efficient | cloud efficiency engineer points north
MFC gets the current time
UART、RS232、RS485、I2C和SPI的介绍
ArrayList analysis 2: pits in ITR, listiterator, and sublist
Angled detection frame | calibrated depth feature for target detection (with implementation source code)
Linux 下安装 redis
Go自定义排序
Xcode real machine debugging
What are the recommended thesis translation software?
What are the projects of metauniverse and what are the companies of metauniverse
[shutter] open the third-party shutter project
sysdig分析容器系统调用
【单片机项目实训】八路抢答器
Is there a specific format for English papers?
Interpretation of new plug-ins | how to enhance authentication capability with forward auth
Bigder: how to deal with the bugs found in the 32/100 test if they are not bugs
英文论文有具体的格式吗?