首页 文章资讯内容详情

MongoDB学习笔记~MongoDBRepository仓储的实现

2026-05-31 2 花语

本文内容纲要:

回到目录

仓储大叔,只要是持久化的东西,都要把它和仓储撤上关系,为啥,为的是开发人员在使用时统一,高可用及方便在各种方式之间实现动态的切换,如ef与redis和mongoDB的切换,你完成可以通过IRepository接口再配合IOC来实现,方便致极!

之间写过一个redis仓储和xml仓储,感兴趣的同学可以先去看看,呵呵。

MongoDB在实现仓储时,先要知道一些概念,即它的一些connectionstring,即连接串

<connectionStrings> <addname="NormTests"connectionString="mongodb://Username:Password@server:port/dbName/query"/> </connectionStrings>

对于大叔的MongoDBRepository,把它进行了拆分,使用Appsetting进行分别的设置

<appSettingsfile="config.user"> <addkey="MongoDB_Host"value="localhost:27017"/> <addkey="MongoDB_DbName"value=""/> <addkey="MongoDB_UserName"value=""/> <addkey="MongoDB_Password"value=""/> </appSettings>

如果要配置读写分离,那么第一个host为主库,后面的为从库,如下面的字符串,将写操作定在主库,读操作定在各个从库

mongodb://server1,server2,server3/?slaveOk=true

下面看一下源代码

namespaceMongoDb.Data.Core { ///<summary> ///通过MongoDb实现数据的持久化 ///</summary> ///<typeparamname="TEntity"></typeparam> publicclassMongoDBRepository<TEntity>: IExtensionRepository<TEntity>whereTEntity:class { #regionConnectionString privatestaticreadonlystring_connectionStringHost=ConfigurationManager.AppSettings["host"]; privatestaticreadonlystring_dbName=ConfigurationManager.AppSettings["dbName"]; privatestaticreadonlystring_userName=ConfigurationManager.AppSettings["userName"]; privatestaticreadonlystring_password=ConfigurationManager.AppSettings["password"]; publicstaticstringConnectionString(stringoptions) { vardatabase=_dbName; varuserName=_userName; varpassword=_password; varauthentication=string.Empty; varhost=string.Empty; if(userName!=null) { authentication=string.Concat(userName,:,password,@); } if(!string.IsNullOrEmpty(options)&&!options.StartsWith("?")) { options=string.Concat(?,options); } host=string.IsNullOrEmpty(_connectionStringHost)?"localhost":_connectionStringHost; database=database??"Test"; //mongodb://[username:password@]host1[:port1][,host2[:port2],…[,hostN[:portN]]][/[database][?options]] returnstring.Format("mongodb://{0}{1}/{2}{3}?{4}",authentication,host,database,options); } publicstaticstringConnectionString() { returnConnectionString(null); } #endregion #regionPublicProperties publicIMongoCollection<TEntity>Table { get { using(varmongo=Mongo.Create(ConnectionString())) { returnmongo.Database.GetCollection<TEntity>(typeof(TEntity).Name); } } } #endregion #regionIRepository<TEntity>成员 publicvoidSetDbContext(IUnitOfWorkunitOfWork) { thrownewNotImplementedException(); } publicvoidInsert(TEntityitem) { using(varmongo=Mongo.Create(ConnectionString())) { vartable=mongo.Database.GetCollection<TEntity>(typeof(TEntity).Name); table.Insert(item); } } publicvoidDelete(TEntityitem) { using(varmongo=Mongo.Create(ConnectionString())) { vartable=mongo.Database.GetCollection<TEntity>(typeof(TEntity).Name); table.Delete(item); } } publicvoidUpdate(TEntityitem) { using(varmongo=Mongo.Create(ConnectionString())) { vartable=mongo.Database.GetCollection<TEntity>(typeof(TEntity).Name); table.Save(item); } } publicIQueryable<TEntity>GetModel() { using(varmongo=Mongo.Create(ConnectionString())) { returnmongo.Database.GetCollection<TEntity>(typeof(TEntity).Name).AsQueryable(); } } publicTEntityFind(paramsobject[]id) { using(varmongo=Mongo.Create(ConnectionString())) { returnmongo.Database .GetCollection<TEntity>(typeof(TEntity).Name) .Find(new{ID=newObjectId(id[0].ToString())}) .FirstOrDefault(); } } #endregion #regionIExtensionRepository<TEntity>成员 publicvoidInsert(IEnumerable<TEntity>item) { using(varmongo=Mongo.Create(ConnectionString())) { vartable=mongo.Database.GetCollection<TEntity>(typeof(TEntity).Name); item.ToList().ForEach(i=> { table.Insert(i); }); } } publicvoidUpdate(IEnumerable<TEntity>item) { using(varmongo=Mongo.Create(ConnectionString())) { vartable=mongo.Database.GetCollection<TEntity>(typeof(TEntity).Name); item.ToList().ForEach(i=> { table.Save(i); }); } } publicvoidDelete(IEnumerable<TEntity>item) { using(varmongo=Mongo.Create(ConnectionString())) { vartable=mongo.Database.GetCollection<TEntity>(typeof(TEntity).Name); item.ToList().ForEach(i=> { table.Delete(i); }); } } publicvoidUpdate<T>(System.Linq.Expressions.Expression<Action<T>>entity)whereT:class { thrownewNotImplementedException(); } publicIQueryable<TEntity>GetModel(System.Linq.Expressions.Expression<Func<TEntity,bool>>predicate) { using(varmongo=Mongo.Create(ConnectionString())) { returnmongo.Database.GetCollection<TEntity>(typeof(TEntity).Name).AsQueryable().Where(predicate); } } publicTEntityFind(System.Linq.Expressions.Expression<Func<TEntity,bool>>predicate) { using(varmongo=Mongo.Create(ConnectionString())) { returnmongo.Database.GetCollection<TEntity>(typeof(TEntity).Name).AsQueryable().FirstOrDefault(predicate); } } publicvoidBulkInsert(IEnumerable<TEntity>item,boolisRemoveIdentity) { thrownewNotImplementedException(); } publicvoidBulkInsert(IEnumerable<TEntity>item) { thrownewNotImplementedException(); } publicvoidBulkUpdate(IEnumerable<TEntity>item,paramsstring[]fieldParams) { thrownewNotImplementedException(); } publicvoidBulkDelete(IEnumerable<TEntity>item) { thrownewNotImplementedException(); } publiceventAction<SavedEventArgs>AfterSaved; publiceventAction<SavedEventArgs>BeforeSaved; publicIQueryable<TEntity>GetModel(Frameworks.Entity.Core.Specification.ISpecification<TEntity>specification) { thrownewNotImplementedException(); } publicTEntityFind(Frameworks.Entity.Core.Specification.ISpecification<TEntity>specification) { returnGetModel(specification).FirstOrDefault(); } publicIQueryable<TEntity>GetModel(Action<IOrderable<TEntity>>orderBy,Frameworks.Entity.Core.Specification.ISpecification<TEntity>specification) { varlinq=newOrderable<TEntity>(GetModel(specification)); orderBy(linq); returnlinq.Queryable; } #endregion #regionIRepositoryAsync<TEntity>成员 publicTaskInsertAsync(TEntityitem) { thrownewNotImplementedException(); } publicTaskDeleteAsync(TEntityitem) { thrownewNotImplementedException(); } publicTaskUpdateAsync(TEntityitem) { thrownewNotImplementedException(); } publicTaskInsertAsync(IEnumerable<TEntity>item) { thrownewNotImplementedException(); } publicTaskUpdateAsync(IEnumerable<TEntity>item) { thrownewNotImplementedException(); } publicTaskDeleteAsync(IEnumerable<TEntity>item) { thrownewNotImplementedException(); } publicTaskBulkInsertAsync(IEnumerable<TEntity>item,boolisRemoveIdentity) { thrownewNotImplementedException(); } publicTaskBulkInsertAsync(IEnumerable<TEntity>item) { thrownewNotImplementedException(); } publicTaskBulkUpdateAsync(IEnumerable<TEntity>item,paramsstring[]fieldParams) { thrownewNotImplementedException(); } publicTaskBulkDeleteAsync(IEnumerable<TEntity>item) { thrownewNotImplementedException(); } #endregion #regionIOrderableRepository<TEntity>成员 publicIQueryable<TEntity>GetModel(Action<IOrderable<TEntity>>orderBy) { varlinq=newOrderable<TEntity>(GetModel()); orderBy(linq); returnlinq.Queryable; } publicIQueryable<TEntity>GetModel(Action<IOrderable<TEntity>>orderBy,System.Linq.Expressions.Expression<Func<TEntity,bool>>predicate) { varlinq=newOrderable<TEntity>(GetModel(predicate)); orderBy(linq); returnlinq.Queryable; } #endregion } }

回到目录

本文内容总结:

原文链接:https://www.cnblogs.com/lori/p/4402018.html