Using system; using system. collections. generic; using system. LINQ; using MongoDB; // <summary> /// the packaging class for Mongo and 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 s Tatic readonly string _ dbname = connectionstring. split (';') [1]; Public mymongodb (): This (_ connectionstring, _ dbname) {} public mymongodb (string dbname): This (_ connectionstring, dbname) {}/// <summary> /// constructor. Based on the specified connection string and database name /// </Summary> /// <Param name = "connectionstring"> connection string </param> /// <Param name = "dbname ""> Database Name, can be empty, but you must call the usedb () method </param> Public mymongodb (string connectionstring, string dbname) {If (string. isnullorempty (connectionstring) throw new argumentnullexception ("connectionstring"); _ Mongo = new Mongo (connectionstring); // connect mongodb_mongo.connect () immediately; if (string. isnullorempty (dbname) = False) _ DB = _ Mongo. getdatabase (dbname );} /// <summary> /// switch to the specified database /// </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> /// obtain the database currently connected /// </Summary> Public imongodatabase currentdb {get {If (_ DB = NULL) Throw New exception ("no database is specified for the current connection. Specify the database name in the constructor or call usedb () to switch the database. "); Return _ DB ;}} /// <summary> /// obtain the specified set of currently connected databases [by type] /// </Summary> /// <typeparam name = "T"> </ typeparam> // <returns> </returns> Public imongocollection <t> getcollection <t> () where T: Class {return this. currentdb. getcollection <t> ();} /// <summary> /// obtain the specified set of currently connected databases [Based on the specified name] /// </Summary> /// <typeparam name = "T"> </typeparam> /// <Param name = "name"> set 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 ;}}}
Use link class
Public void insert (User user) {using (mymongodb MDB = new mymongodb () {var collection = MDB. getcollection <user> (); Collection. insert (User );}}