当前位置:网站首页>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));
}
}



边栏推荐
- 带角度的检测框 | 校准的深度特征用于目标检测(附实现源码)
- collections. What is the purpose of chainmap- What is the purpose of collections. ChainMap?
- [shutter] shutter open source project reference
- Luogu_ P2010 [noip2016 popularization group] reply date_ Half enumeration
- Pat 1030 travel plan (30 points) (unfinished)
- Don't want teachers to see themselves with cameras in online classes? Virtual camera you deserve!
- Interpretation of new plug-ins | how to enhance authentication capability with forward auth
- Mutual exclusion and synchronization of threads
- 洛谷_P2010 [NOIP2016 普及组] 回文日期_折半枚举
- Seckill system design
猜你喜欢
Container runtime analysis
Feature Engineering: summary of common feature transformation methods
布隆过滤器
Additional: token; (don't read until you finish writing...)
Luogu_ P2010 [noip2016 popularization group] reply date_ Half enumeration
JDBC tutorial
直击产业落地!飞桨重磅推出业界首个模型选型工具
Confluence的PDF导出中文文档异常显示问题解决
How do educators find foreign language references?
Sysdig analysis container system call
随机推荐
The privatization deployment of SaaS services is the most efficient | cloud efficiency engineer points north
[shutter] open the third-party shutter project
关于Unity屏幕相关Screen的练习题目,Unity内部环绕某点做运动
How QT exports data to PDF files (qpdfwriter User Guide)
In February 2022, the ranking list of domestic databases: oceanbase regained its popularity with "three consecutive increases", and gaussdb is expected to achieve the largest increase this month
NC50965 Largest Rectangle in a Histogram
[shutter] shutter open source project reference
Analyze ad654: Marketing Analytics
写论文可以去哪些网站搜索参考文献?
35 pages dangerous chemicals safety management platform solution 2022 Edition
Sysdig analysis container system call
Create an interactive experience of popular games, and learn about the real-time voice of paileyun unity
Pytorch里面多任务Loss是加起来还是分别backward?
Bigder:32/100 测试发现的bug开发认为不是bug怎么处理
Digital twin visualization solution digital twin visualization 3D platform
Define MySQL function to realize multi module call
开源了 | 文心大模型ERNIE-Tiny轻量化技术,又准又快,效果全开
洛谷_P1149 [NOIP2008 提高组] 火柴棒等式_枚举打表
Andorid 获取系统标题栏高度
CADD course learning (4) -- obtaining proteins without crystal structure (Swiss model)