代码改变世界

MongoDB 工具助手类(.NET)

  jiangys  阅读(637)  评论(0编辑  收藏  举报

在开发过程中,需要用到MongoDB,本身MongoDB自己对类的封装就特别好了。为了更加符合我们平时的开发使用,我现在进行了一个简单的封装操作。

连接数据库类:MongoDBContext

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Driver.Linq;

namespace XXXXX.MongoDB
{
    public class MongoDBContext
    {
        // 数据库链接
        private readonly MongoDatabase database;

        public MongoDBContext()
            : this(ConfigurationManager.AppSettings["DefaultMongoDBConnection"], ConfigurationManager.AppSettings["DefaultMonoDbDatabase"])
        {
        }

        /// <summary>
        /// 构造函数。根据指定连接字符串和数据库名
        /// </summary>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="dbName">数据库名</param>
        public MongoDBContext(string connectionString, string dbName)
        {
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentNullException("connectionString is null");
            }

            if (string.IsNullOrEmpty(dbName))
            {
                throw new ArgumentNullException("dbName is null");
            }

            var client = new MongoClient(connectionString);
            var server = client.GetServer();
            this.database = server.GetDatabase(dbName);
        }

        /// <summary>
        /// 获取当前连接数据库的指定集合【依据类型】
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public MongoCollection<T> Collection<T>()
        {
            return database.GetCollection<T>(typeof(T).Name);
        }
    }
}
复制代码

服务操作类:MongoDBService

复制代码
using MongoDB.Driver.Builders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace XXXXX.MongoDB
{

    public class MongoDBService<T> : IMongoDBService<T> where T : class,new()
    {
        MongoDBContext mc = new MongoDBContext();

        /// <summary>
        /// 查询符合条件的集合
        /// </summary>
        /// <param name="whereLambda"></param>
        /// <returns></returns>
        public IEnumerable<T> GetList()
        {
            var query = Query<T>.Where(o => true);
            return mc.Collection<T>().Find(query);
        }

        /// <summary>
        /// 查询符合条件的集合
        /// </summary>
        /// <param name="whereLambda"></param>
        /// <returns></returns>
        public IEnumerable<T> GetList(Expression<Func<T, bool>> whereLambda)
        {
            var query = Query<T>.Where(whereLambda);
            return mc.Collection<T>().Find(query);
        }

        /// <summary>
        /// 查询一条记录
        /// </summary>
        /// <param name="whereLambda"></param>
        /// <returns></returns>
        public T GetOne(Expression<Func<T, bool>> whereLambda)
        {
            var query = GetList(whereLambda).FirstOrDefault();
            return query;
        }

        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="entity"></param>
        public void Insert(T entity)
        {
            mc.Collection<T>().Insert(entity);
        }

        /// <summary>
        /// 批量增加
        /// </summary>
        /// <param name="entitys"></param>
        public void InsertAll(IEnumerable<T> entitys)
        {
            mc.Collection<T>().InsertBatch(entitys);
        }

        /// <summary>
        /// 更新一个实体
        /// </summary>
        /// <param name="entity"></param>
        public void Update(T entity)
        {
            mc.Collection<T>().Save(entity);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="whereLambda"></param>
        public void Remove(Expression<Func<T, bool>> whereLambda)
        {
            var query = Query<T>.Where(whereLambda);
            mc.Collection<T>().Remove(query);
        }
    }
}
复制代码

上面方法封装完后,我们就可以直接使用了。使用很简单,比如,我有一个ActivityModel实体,使用时,如下:

        public void activityTest()
        {
            var activityDb = new MongoDBService<ActivityModel>();
            var activityList = activityDb.GetList().ToList();
            var activity = activityDb.GetOne(o => o.Id==ObjectId.Parse("54d9aecd89f0bd14d81a63a7"));
            var xxx = activity.To();
        }

 

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
点击右上角即可分享
微信分享提示