csharp实现MongoDB的增删改查

谷梁镜
2023-12-01
一直在找个csharp的Mongodb帮助文档,官网的说的太少了。可惜找不到。
学习别人的代码,复制过来。

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Linq;usingMongoDB.Bson;usingMongoDB.Driver;usingMongoDB.Attributes;usingMongoDB.Configuration;usingSystem.Linq.Expressions;usingMongoDB;usingMongoDB.Linq;namespace showPicture1{    classMongodbHelper    {        string connectionString =string.Empty;        string databaseName =string.Empty;        string collectionName =string.Empty;        //static MongodbHelper<T> mongodb;        #region 初始化操作        /// <summary>        /// 初始化操作        /// </summary>        publicMongodbHelper()        {            connectionString ="mongodb://localhost";            //创建数据连接            databaseName ="shopex";            //获取指定数据库            collectionName ="person";            //获取表        }        #endregion        #region 实现linq查询的映射配置        /// <summary>        /// 实现linq查询的映射配置        /// </summary>        publicMongoConfiguration configuration        {            get            {                var config =newMongoConfigurationBuilder();                config.Mapping(mapping =>                {                    mapping.DefaultProfile(profile =>                    {                        profile.SubClassesAre(t => t.IsSubclassOf(typeof(T)));                    });                    mapping.Map<T>();                    mapping.Map<T>();                });                config.ConnectionString(connectionString);                return config.BuildConfiguration();            }        }        #endregion        #region 插入操作        /// <summary>        /// 插入操作        /// </summary>        /// <param name="person"></param>        /// <returns></returns>        publicvoidInsert(T t)        {            using(Mongo mongo =newMongo(configuration))            {                try                {                    mongo.Connect();                    var db = mongo.GetDatabase(databaseName);                    var collection = db.GetCollection<T>(collectionName);                    collection.Insert(t,true);                    mongo.Disconnect();                }                catch(Exception)                {                    mongo.Disconnect();                    throw;                }            }        }        #endregion        #region 更新操作        /// <summary>        /// 更新操作        /// </summary>        /// <param name="person"></param>        /// <returns></returns>        publicvoidUpdate(T t,Expression<Func<T,bool>> func)        {            using(Mongo mongo =newMongo(configuration))            {                try                {                    mongo.Connect();                    var db = mongo.GetDatabase(databaseName);                    var collection = db.GetCollection<T>(collectionName);                    collection.Update<T>(t, func,true);                    mongo.Disconnect();                }                catch(Exception)                {                    mongo.Disconnect();                    throw;                }            }        }        #endregion        #region 获取集合        /// <summary>        ///获取集合        /// </summary>        /// <param name="person"></param>        /// <returns></returns>        publicList<T>List(int pageIndex,int pageSize,Expression<Func<T,bool>> func,outint pageCount)        {            pageCount =0;            using(Mongo mongo =newMongo(configuration))            {                try                {                    mongo.Connect();                    var db = mongo.GetDatabase(databaseName);                    var collection = db.GetCollection<T>(collectionName);                    pageCount =Convert.ToInt32(collection.Count());                    var personList = collection.Linq().Where(func).Skip(pageSize *(pageIndex -1))                    .Take(pageSize).Select(i => i).ToList();                    mongo.Disconnect();                    return personList;                }                catch(Exception)                {                    mongo.Disconnect();                    throw;                }            }        }        #endregion        #region 读取单条记录        /// <summary>        ///读取单条记录        /// </summary>        /// <param name="person"></param>        /// <returns></returns>        public T Single(Expression<Func<T,bool>> func)        {            using(Mongo mongo =newMongo(configuration))            {                try                {                    mongo.Connect();                    var db = mongo.GetDatabase(databaseName);                    var collection = db.GetCollection<T>(collectionName);                    var single = collection.Linq().FirstOrDefault(func);                    mongo.Disconnect();                    return single;                }                catch(Exception)                {                    mongo.Disconnect();                    throw;                }            }        }        #endregion        #region 删除操作        /// <summary>        /// 删除操作        /// </summary>        /// <param name="person"></param>        /// <returns></returns>        publicvoidDelete(Expression<Func<T,bool>> func)        {            using(Mongo mongo =newMongo(configuration))            {                try                {                    mongo.Connect();                    var db = mongo.GetDatabase(databaseName);                    var collection = db.GetCollection<T>(collectionName);                    //这个地方要注意,一定要加上T参数,否则会当作object类型处理                    //导致删除失败                    collection.Remove<T>(func);                    mongo.Disconnect();                }                catch(Exception)                {                    mongo.Disconnect();                    throw;                }            }        }        #endregion    }

 类似资料: