封裝一個MongoDB的 asp.net 連結類

來源:互聯網
上載者:User
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);            }        }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.