c# 操作monogodb的一些简单封装
public interface IDataBaseCore
{
}
public class BasicData : IDataBaseCore
{
}
public class Filter
{
public string Key { set; get; }
public string Value { set; get; }
}
/// <summary> /// 数据Context接口 /// </summary> public interface IDataContext<T> where T : class { /// <summary> /// 客户端数据连接访问器 /// </summary> T DbContext { set; get; } }
public interface IDataBase<T> : IDataContext<MongoClient> where T : IDataBaseCore
{
/// <summary>
/// 数据库
/// </summary>
IMongoDatabase DataBase { get;}
}
public class MongodbContext<T> : IDataBase<T> where T : IDataBaseCore
{
public MongodbContext()
{
}
public MongoClient DbContext { set; get; } = new MongoClient(new ConfigSetting().Mongodb);
public IMongoDatabase DataBase { get => DbContext.GetDatabase(typeof(T).Name); }
#region 具体的表操作
/// <summary>
/// 系统菜单
/// </summary>
public IMongoCollection<SysMenu> SysMenus { get => DbSet<SysMenu>(); }
/// <summary>
/// 用户
/// </summary>
public IMongoCollection<User> Users { set; get; }
#endregion
public IMongoCollection<K> DbSet<K>() where K : ICore => DataBase.GetCollection<K>(typeof(K).Name);
}
monogodb链接对象是自托管不用考虑链接释放问题,当然做成单利的也是可以的 原本typeof(K).Name 这里是写的是nameof(K)发现无法得到真实传递K的Name名称 直接解释成了字符串K。
扩展方法
public static class MongodbExpansion
{
/// <summary>
/// 单个对象添加
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="entity"></param>
public static void Add<T>(this IMongoCollection<T> collection, T entity) where T : ICore
=> collection.InsertOne(entity);
/// <summary>
/// 单个对象异步操作
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="entity"></param>
/// <returns></returns>
public static async Task AddAsync<T>(this IMongoCollection<T> collection, T entity) where T : ICore
=> await collection.InsertOneAsync(entity);
/// <summary>
/// 集合添加
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="entitys"></param>
public static void AddRange<T>(this IMongoCollection<T> collection, List<T> entitys) where T : ICore
=> collection.InsertMany(entitys);
/// <summary>
/// 集合异步操作
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="entitys"></param>
public static void AddRangeAsync<T>(this IMongoCollection<T> collection, List<T> entitys) where T : ICore
=> collection.InsertManyAsync(entitys);
/// <summary>
/// entity mongodb需要更新的实体 properts需要更新的集合属性,大小写不限 默认更新整个对象 replace 默认空属性不修改
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="entity">mongodb需要更新的实体</param>
/// <param name="properts">需要更新的集合属性,大小写不限 默认更新整个对象 </param>
/// <param name="replace">默认空属性不修改</param>
public static void Update<T>(this IMongoCollection<T> collection, T entity, List<string> properts = null, bool replace = false) where T : ICore
{
if (entity == null)
throw new NullReferenceException();
var type = entity.GetType();
///修改的属性集合
var list = new List<UpdateDefinition<T>>();
foreach (var propert in type.GetProperties())
{
if (propert.Name.ToLower() != "id")
{
|| properts.Any(o => o.ToLower() == propert.Name.ToLower()))
{
var replaceValue = propert.GetValue(entity);
if (replaceValue != null)
list.Add(Builders<T>.Update.Set(propert.Name, replaceValue));
else if (replace)
list.Add(Builders<T>.Update.Set(propert.Name, replaceValue));
}
}
}
#region 有可修改的属性
)
{
var builders = Builders<T>.Update.Combine(list);
collection.UpdateOne(o => o.Id == entity.Id, builders);
}
#endregion
}
/// <summary>
/// 异步等同Update方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="entity"></param>
/// <param name="properts"></param>
/// <param name="replace"></param>
/// <returns></returns>
public static async Task UpdateAsync<T>(this IMongoCollection<T> collection, T entity, List<string> properts = null, bool replace = false) where T : ICore
{
if (entity == null)
throw new NullReferenceException();
var type = entity.GetType();
///修改的属性集合
var list = new List<UpdateDefinition<T>>();
foreach (var propert in type.GetProperties())
{
if (propert.Name.ToLower() != "id")
{
|| properts.Any(o => o.ToLower() == propert.Name.ToLower()))
{
var replaceValue = propert.GetValue(entity);
if (replaceValue != null)
list.Add(Builders<T>.Update.Set(propert.Name, replaceValue));
else if (replace)
list.Add(Builders<T>.Update.Set(propert.Name, replaceValue));
}
}
}
#region 有可修改的属性
)
{
var builders = Builders<T>.Update.Combine(list);
await collection.UpdateOneAsync(o => o.Id == entity.Id, builders);
}
#endregion
}
public static void Remove<T>(this IMongoCollection<T> collection, T entity) where T : ICore
=> collection.DeleteOne(o => o.Id == entity.Id);
public static void RemoveById<T>(this IMongoCollection<T> collection, string id) where T : ICore
=> collection.DeleteOne(Builders<T>.Filter.Eq("Id", id));
public static async Task RemoveAsync<T>(this IMongoCollection<T> collection, T entity) where T : ICore
=> await collection.DeleteOneAsync(o => o.Id == entity.Id);
public static async Task RemoveAsyncById<T>(this IMongoCollection<T> collection, string id) where T : ICore
=> await collection.DeleteOneAsync(Builders<T>.Filter.Eq("Id", id));
public static FilterDefinition<T> CombineToFilter<T>(this List<FilterDefinition<T>> list)
=> Builders<T>.Filter.And(list);
public static void RemoveRange<T>(this IMongoCollection<T> collection, List<T> entitys) where T : ICore
{
)
throw new NullReferenceException();
collection.DeleteMany(Builders<T>.Filter.In("Id", entitys.Select(o => o.Id)));
}
public static async Task RemoveRangeAsync<T>(this IMongoCollection<T> collection, List<T> entitys) where T : ICore
{
)
throw new NullReferenceException();
await collection.DeleteManyAsync(Builders<T>.Filter.In("Id", entitys.Select(o => o.Id)));
}
public static T FindDefault<T>(this IMongoCollection<T> collection, string Id) where T : ICore
=> collection.Find(o => o.Id == Id).FirstOrDefault();
public static IList<T> FindAll<T>(this IMongoCollection<T> collection, bool sort = false) where T : ICore
=> sort ? collection.Find(Builders<T>.Filter.Empty).SortBy(o => o.CreateTime).ToList() : collection.Find(Builders<T>.Filter.Empty).ToList();
public static IList<T> FindAllSort<T>(this IMongoCollection<T> collection, Expression<Func<T, object>> sort = null) where T : ICore
=> sort == null ? collection.Find(Builders<T>.Filter.Empty).ToList() : collection.Find(Builders<T>.Filter.Empty).SortBy(sort).ToList();
public static IFindFluent<T, T> FindDefault<T>(this IMongoCollection<T> collection) where T : ICore
=> collection.Find(Builders<T>.Filter.Empty);
public static IFindFluent<T, T> Where<T>(this IMongoCollection<T> collection, Expression<Func<T, bool>> where) where T : ICore
=> where == null ? collection.Find(Builders<T>.Filter.Empty) : collection.Find(where);
public static IFindFluent<TDocument, TNewProjection> Select<TDocument, TProjection, TNewProjection>(this IFindFluent<TDocument, TProjection> IQueryable, Expression<Func<TDocument, TNewProjection>> projection)
=> IQueryable.Project(projection);
public static IFindFluent<TDocument, TNewProjection> PageSize<TDocument, TNewProjection>(this IFindFluent<TDocument, TNewProjection> IQueryable, Search search)
=> IQueryable.Skip((search.Args.PageIndex - ) * search.Args.PageSize).Limit(search.Args.PageSize);
}
仓储
public interface IRepository<T> where T : ICore
{
/// <summary>
/// 查询单个对象
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
T FindById(string id);
/// <summary>
/// 查询单个对象
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
T FirstOrDefault(System.Linq.Expressions.Expression<Func<T, bool>> where);
IFindFluent<T, T> FindFiter(FilterDefinition<T> filter);
/// <summary>
/// 获取所有
/// </summary>
/// <returns></returns>
IList<T> GetList();
/// <summary>
/// 根据条件查询所有
/// </summary>
/// <param name="where"></param>
/// <returns></returns>
IList<T> GetList(System.Linq.Expressions.Expression<Func<T, bool>> where);
IList<T> GetListOrderBy();
/// <summary>
/// 单个实体
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
void Insert(T entity);
/// <summary>
/// 批量添加
/// </summary>
/// <param name="entitys"></param>
/// <returns></returns>
void BulkInsert(List<T> entitys);
/// <summary>
/// 修改单个实体
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
void Update(T entity);
/// <summary>
/// 批量修改
/// </summary>
/// <param name="entitys"></param>
/// <returns></returns>
void BulkUpdate(List<T> entitys);
Result AddResultEntity(T t);
Result UpdateResultEntity(T t, List<string> propertys = null, bool replace = false);
Result RemoveResultEntity(T t);
FilterDefinition<T> ConverToFilter(Filter filter);
PageArgs GetPageArgs(Search search);
}
实现
public abstract class Repository<T, K> : IRepository<K> where T : IDataBaseCore where K : ICore
{
public Repository()
{
if (MongodbContext == null)
MongodbContext = new MongodbContext<T>();
}
protected IMongoCollection<K> Collection { get => MongodbContext.DbSet<K>(); }
protected FilterDefinition<K> FilterEmpty { set; get; } = Builders<K>.Filter.Empty;
protected static MGDataChannel.Realize.MongodbContext<T> MongodbContext { set; get; }
public K FindById(string id)
=> MongodbContext.DbSet<K>().FindDefault(id);
public K FirstOrDefault(Expression<Func<K, bool>> where)
=> MongodbContext.DbSet<K>().Find(where).FirstOrDefault();
public IFindFluent<K, K> FindFiter(FilterDefinition<K> filter)
=> MongodbContext.DbSet<K>().Find(filter);
public async Task<IAsyncCursor<K>> FindFiterAsync(FilterDefinition<K> filter)
=> await MongodbContext.DbSet<K>().FindAsync(filter);
public virtual IList<K> GetList()
=> MongodbContext.DbSet<K>().Find(Builders<K>.Filter.Empty).ToList();
public virtual IList<K> GetListOrderBy()
=> MongodbContext.DbSet<K>().Find(Builders<K>.Filter.Empty).SortBy(o => o.CreateTime).ToList();
public virtual IList<K> GetList(Expression<Func<K, bool>> where)
=> MongodbContext.DbSet<K>().Find(where).ToList();
public virtual FilterDefinition<K> ConverToFilter(Filter filter)
{
if (!string.IsNullOrEmpty(filter.Value))
{
if (filter.Key.ToLower() == "id")
return Builders<K>.Filter.Eq("Id", filter.Value);
else if (filter.Key.ToLower() == "name")
return Builders<K>.Filter.Where(o => o.Name.Contains(filter.Value.ToString()));
else if (filter.Key.ToLower() == "stardate")
return Builders<K>.Filter.Gte("StarDate", Convert.ToDateTime(filter.Value));//$gte
else if (filter.Key.ToLower() == "enddate")
return Builders<K>.Filter.Lte("EndDate", Convert.ToDateTime(filter.Value));//$gte
}
return Builders<K>.Filter.Empty;
}
protected virtual FilterDefinition<K> GetFilters(Search search, Func<Filter, FilterDefinition<K>> fun)
{
var filters = new List<FilterDefinition<K>>();
search.Filters.ForEach(o =>
{
filters.Add(fun(o));
});
)
return Builders<K>.Filter.Empty;
///过滤条件合并
var filter = filters.CombineToFilter();
return filter;
}
public virtual void Insert(K entity)
=> MongodbContext.DbSet<K>().Add(entity);
public virtual void BulkInsert(List<K> entitys)
=> MongodbContext.DbSet<K>().AddRange(entitys);
public virtual void Update(K entity)
=> MongodbContext.DbSet<K>().Update(entity);
public virtual void Update(K entity, List<string> propertys = null, bool replace = false)
=> MongodbContext.DbSet<K>().Update(entity, propertys, replace);
public virtual void BulkUpdate(List<K> entitys)
{
throw new NotImplementedException();
}
public virtual Result AddResultEntity(K t)
{
Insert(t);
return new Result(true, t, "");
}
public virtual Result UpdateResultEntity(K t, List<string> propertys = null, bool replace = false)
{
Update(t, propertys, replace);
return new Result(true, t, "");
}
public virtual Result RemoveResultEntity(K t)
{
throw new NotImplementedException();
}
public virtual PageArgs GetPageArgs(Search search)
{
///获取过滤条件
var filter = this.GetFilters(search, this.ConverToFilter);
var query = this.FindFiter(filter);
///总记录数
int recordCount = (int)query.Count();
PageArgs args = new PageArgs(recordCount, search.Args.PageIndex, search.Args.PageSize);
)
{
var data = query.PageSize(search).ToList();
args.Data = data;
}
return args;
}
}
此客户端驱动是基于最新的mongodbC#客户端驱动封装的 可能和以前的一些方法不太一样
c# 操作monogodb的一些简单封装的更多相关文章
- C#操作SQLServer的一个简单封装
class DBHandler { //SqlConnection数据库连接对象 private SqlConnection localConnection = null; //构造函数中初始化连接对 ...
- Golang 对MongoDB的操作简单封装
使用MongoDB的Go驱动库 mgo,对MongoDB的操作做一下简单封装 初始化 操作没有用户权限的MongoDB var globalS *mgo.Session func init() { s ...
- redis数据库操作的C++简单封装
用c++简单封装了redis的基本操作(hiredis) 接口包括:①链接和断开连接.②设置键值对(set).③查询键值对(get).④删除键值对(del).⑤将所有键显示出来 若任何一处发生错误,返 ...
- Android AsyncTask 深度理解、简单封装、任务队列分析、自定义线程池
前言:由于最近在做SDK的功能,需要设计线程池.看了很多资料不知道从何开始着手,突然发现了AsyncTask有对线程池的封装,so,就拿它开刀,本文将从AsyncTask的基本用法,到简单的封装,再到 ...
- FMDB简单封装和使用
工具:火狐浏览器+SQLite Manager插件 ; Xcode; FMDB库; 效果: 项目地址: https://github.com/sven713/PackFMDB 主要参考这两篇博客: 1 ...
- OracleHelper(对增删改查分页查询操作进行了面向对象的封装,对批量增删改操作的事务封装)
公司的一个新项目使用ASP.NET MVC开发,经理让我写个OracleHelper,我从网上找了一个比较全的OracleHelper类,缺点是查询的时候返回DataSet,数据增删改要写很多代码(当 ...
- iOS sqlite 增删改查 简单封装(基于 FMDB)
/** * 对 sqlite 的使用进行简单封装,仅涉及简单的单表 增删改查 * * 基于 FMDB * * 操作基于 model ,数据库表字段与 model 属性一一对应,对 model 整 ...
- ADO简单封装(MFC)
简单封装了一下,不是很严谨. /************************************************************************/ /* INSTRUC ...
- MySQL的C++简单封装
/* *介绍:MySQL的简单封装,支持流操作输入输出MySQL语句,然而并没有什么软用,大二学生自娱自乐,有不足求指点 *作者:MrEO *日期:2016.3.26 */ 头文件 my_sql.h ...
随机推荐
- Windows搭建以太坊的私有链环境
1.下载Geth.exe 运行文件,并安装 https://github.com/ethereum/go-ethereum/releases/ 下载后,只有一个Geth.exe的文件 2.cmd进入按 ...
- 构建高性能web站点-阅读笔记(一)
看完前9章,也算是看完一半了吧,总结一下. 郭欣这个名字或许并不响亮,但是这本书写的确实真好!百度一下他的名字也能够看到他是某些公司的创始人和投资者,当然他本人必定是大牛无疑. 从网页的动静分离到网络 ...
- 较简单的用ajax修改和添加功能(链接数据库)
修改和添加关于数据库的信息,可以用于任何的添加和修改 这些数据库和前面的随笔数据库是一样的 一.显示出数据库中的信息 (1)显示的效果也可以是用bootstrap的标签页显示(前面一定要引入boots ...
- sql server删除主键约束所想到的
从网上找到了下面一段代码: declare @Pk varchar(100);select @Pk=Name from sysobjects where Parent_Obj=OBJECT_ID('表 ...
- STM32驱动OV7725摄像头颜色识别
实验目的: 使用stm32驱动OV7725摄像头进行图像实时采集,在tft屏幕上实时显示并识别图像中的特定颜色,在颜色的周围画上框. 实验现象: 我的工程代码链接: http://download.c ...
- Java Level 2 学习的八大名著
Java Level 2 学习的八大名著 前段时间有几天难得的假期,于是把自己认为Java技术栈中的精华总结了一下,但是一直没有时间写下来,今天终于得空希望本文可以对大家有所启发.通过多个实际项目的沉 ...
- jquery的冒泡事件event.stopPropagation()
js中的冒泡事件与事件监听 冒泡事件 js中“冒泡事件”并不是能实际使用的花哨技巧,它是一种对js事件执行顺序的机制,“冒泡算法”在编程里是一个经典问题,冒泡算法里面的冒泡应该 说是交换更加准确:js ...
- vue实现简单表格组件
本来想这一周做一个关于vuex的总结的,但是由于朋友反应说还不知道如何用vue去写一个组件,所以在此写写一篇文章来说明下如何去写vue页面或者组件.vue的核心思想就是组件,什么是组件呢?按照我的理解 ...
- redis 数据库实现
redis 数据库实现 数据库的 server 端和 client 端 server 端 数据库在 server 端的存储 // redisServer 结构 struct redisServer { ...
- nginx下的几种包管理器
一般来说著名的linux系统基本上分两大类: 1.RedHat系列:Redhat.Centos.Fedora等 2.Debian系列:Debian.Ubuntu等 RedHat系列: 1 ...