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


边栏推荐
- form表单实例化
- Don't want teachers to see themselves with cameras in online classes? Virtual camera you deserve!
- What website can you find English literature on?
- 论文的英文文献在哪找(除了知网)?
- 写论文可以去哪些网站搜索参考文献?
- collections. What is the purpose of chainmap- What is the purpose of collections. ChainMap?
- MATLAB signal processing [Q & a notes-1]
- Angled detection frame | calibrated depth feature for target detection (with implementation source code)
- Interface automation coverage statistics - used by Jacobo
- leetcode 650. 2 keys keyboard with only two keys (medium)
猜你喜欢

Should you study kubernetes?

Mutual exclusion and synchronization of threads

Bloom filter
![Luogu_ P2010 [noip2016 popularization group] reply date_ Half enumeration](/img/a3/55bb71d39801ceeee421a0c8ded333.png)
Luogu_ P2010 [noip2016 popularization group] reply date_ Half enumeration

sysdig分析容器系统调用

The privatization deployment of SaaS services is the most efficient | cloud efficiency engineer points north

Container runtime analysis

Feature Engineering: summary of common feature transformation methods

What are the projects of metauniverse and what are the companies of metauniverse

Improvement of RTP receiving and sending PS stream tool (II)
随机推荐
基于OpenCV实现口罩识别
在线预览Word文档
MFC file operation
form表单实例化
SQL query statement parameters are written successfully
Question e: merged fruit -noip2004tgt2
多进程编程(三):消息队列
Understanding and application of least square method
[shutter] image component (image component introduction | image constructor | image.network constructor | image.asset constructor)
监控容器运行时工具Falco
[shutter] Introduction to the official example of shutter Gallery (project introduction | engineering construction)
论文的英文文献在哪找(除了知网)?
Don't want teachers to see themselves with cameras in online classes? Virtual camera you deserve!
有哪些比较推荐的论文翻译软件?
Many to one, one to many processing
Where can I check the foreign literature of economics?
教育学大佬是怎么找外文参考文献的?
Markdown使用教程
QT 如何将数据导出成PDF文件(QPdfWriter 使用指南)
Realization of mask recognition based on OpenCV