MongoDB 工具助手类(.NET)

在开发过程中,需要用到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();
        }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。