標籤:
using System;
using System.Collections.Generic;
using System.Linq;
using MongoDB;
/// <summary>
/// 對Mongo和MongoDatabase的封裝類
/// </summary>
public class MyMongoDb : IDisposable
{
private Mongo _mongo;
private IMongoDatabase _db;
private static string connectionString = "Server=127.0.0.1;mydb";
private static readonly string _connectionString = connectionString.Split(‘;‘)[0];// "Server=127.0.0.1";
private static readonly string _dbName = connectionString.Split(‘;‘)[1];
public MyMongoDb()
: this(_connectionString, _dbName)
{
}
public MyMongoDb(string dbName)
: this(_connectionString, dbName)
{
}
/// <summary>
/// 建構函式。根據指定連接字串和資料庫名
/// </summary>
/// <param name="connectionString">連接字串</param>
/// <param name="dbName">資料庫名,可為空白,但必須在任何操作資料庫之前要調用UseDb()方法</param>
public MyMongoDb(string connectionString, string dbName)
{
if( string.IsNullOrEmpty(connectionString) )
throw new ArgumentNullException("connectionString");
_mongo = new Mongo(connectionString);
// 立即串連 MongoDB
_mongo.Connect();
if( string.IsNullOrEmpty(dbName) == false )
_db = _mongo.GetDatabase(dbName);
}
/// <summary>
/// 切換到指定的資料庫
/// </summary>
/// <param name="dbName"></param>
/// <returns></returns>
public IMongoDatabase UseDb(string dbName)
{
if( string.IsNullOrEmpty(dbName) )
throw new ArgumentNullException("dbName");
_db = _mongo.GetDatabase(dbName);
return _db;
}
/// <summary>
/// 擷取當前串連的資料庫
/// </summary>
public IMongoDatabase CurrentDb
{
get
{
if( _db == null )
throw new Exception("當前串連沒有指定任何資料庫。請在建構函式中指定資料庫名或者調用UseDb()方法切換資料庫。");
return _db;
}
}
/// <summary>
/// 擷取當前串連資料庫的指定集合【依據類型】
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public IMongoCollection<T> GetCollection<T>() where T : class
{
return this.CurrentDb.GetCollection<T>();
}
/// <summary>
/// 擷取當前串連資料庫的指定集合【根據指定名稱】
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="name">集合名稱</param>
/// <returns></returns>
public IMongoCollection<T> GetCollection<T>(string name) where T : class
{
return this.CurrentDb.GetCollection<T>(name);
}
public void Dispose()
{
if( _mongo != null ) {
_mongo.Dispose();
_mongo = null;
}
}
}
使用封裝類
public void Insert(USER user)
{
using (MyMongoDb mdb = new MyMongoDb())
{
var collection = mdb.GetCollection<USER>();
collection.Insert(user);
}
}
封裝MongoDB的 asp.net 連結類