在开发过程中,需要用到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"]) { } ////// 构造函数。根据指定连接字符串和数据库名 /// /// 连接字符串 /// 数据库名 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); } ////// 获取当前连接数据库的指定集合【依据类型】 /// ////// public MongoCollection Collection () { return database.GetCollection (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: IMongoDBService where T : class,new() { MongoDBContext mc = new MongoDBContext(); /// /// 查询符合条件的集合 /// /// ///public IEnumerable GetList() { var query = Query .Where(o => true); return mc.Collection ().Find(query); } /// /// 查询符合条件的集合 /// /// ///public IEnumerable GetList(Expression > whereLambda) { var query = Query .Where(whereLambda); return mc.Collection ().Find(query); } /// /// 查询一条记录 /// /// ///public T GetOne(Expression > whereLambda) { var query = GetList(whereLambda).FirstOrDefault(); return query; } /// /// 增加 /// /// public void Insert(T entity) { mc.Collection().Insert(entity); } /// /// 批量增加 /// /// public void InsertAll(IEnumerableentitys) { mc.Collection ().InsertBatch(entitys); } /// /// 更新一个实体 /// /// public void Update(T entity) { mc.Collection().Save(entity); } /// /// 删除 /// /// public void Remove(Expression> whereLambda) { var query = Query .Where(whereLambda); mc.Collection ().Remove(query); } }}
上面方法封装完后,我们就可以直接使用了。使用很简单,比如,我有一个ActivityModel实体,使用时,如下:
public void activityTest() { var activityDb = new MongoDBService(); var activityList = activityDb.GetList().ToList(); var activity = activityDb.GetOne(o => o.Id==ObjectId.Parse("54d9aecd89f0bd14d81a63a7")); var xxx = activity.To(); }