MongoDB學習筆(bi)記~MongoDBRepository倉儲的實現
倉儲(chu)(chu)大叔,只要是持久化(hua)的東西,都要把它和倉儲(chu)(chu)撤上關系,為啥(sha),為的是開發(fa)人員在使用時(shi)統一(yi),高可用及方便(bian)(bian)在各(ge)種(zhong)方式之間實(shi)現動(dong)態(tai)的切換,如ef與redis和mongoDB的切換,你(ni)完成可以通過(guo)IRepository接(jie)口(kou)再配合(he)IOC來實(shi)現,方便(bian)(bian)致極(ji)!
之間寫過一個redis倉儲和xml倉儲,感興趣的同學可(ke)以(yi)先去看看,呵(he)呵(he)。
MongoDB在實現(xian)倉儲時,先要(yao)知(zhi)道(dao)一些概念,即它的一些connectionstring,即連接串(chuan)
<connectionStrings>
<add name="NormTests" connectionString="mongodb://Username:Password@server:port/dbName/query"/>
</connectionStrings>
對于大叔的MongoDBRepository,把它進行(xing)了拆(chai)分,使用Appsetting進行(xing)分別(bie)的設置
<appSettings file="config.user"> <add key="MongoDB_Host" value="localhost:27017"/>
<add key="MongoDB_DbName" value=""/>
<add key="MongoDB_UserName" value=""/>
<add key="MongoDB_Password" value=""/>
</appSettings>
如(ru)果要配置讀寫分離,那么第一個(ge)host為主庫(ku),后面(mian)(mian)的為從庫(ku),如(ru)下面(mian)(mian)的字符(fu)串(chuan),將(jiang)寫操作(zuo)定在(zai)(zai)主庫(ku),讀操作(zuo)定在(zai)(zai)各個(ge)從庫(ku)
mongodb://server1,server2,server3/?slaveOk=true
下面看一下源代碼
namespace MongoDb.Data.Core { /// <summary> /// 通過(guo)MongoDb實(shi)現數據的持(chi)久化 /// </summary> /// <typeparam name="TEntity"></typeparam> public class MongoDBRepository<TEntity> : IExtensionRepository<TEntity> where TEntity : class { #region ConnectionString private static readonly string _connectionStringHost = ConfigurationManager.AppSettings["host"]; private static readonly string _dbName = ConfigurationManager.AppSettings["dbName"]; private static readonly string _userName = ConfigurationManager.AppSettings["userName"]; private static readonly string _password = ConfigurationManager.AppSettings["password"]; public static string ConnectionString(string options) { var database = _dbName; var userName = _userName; var password = _password; var authentication = string.Empty; var host = 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]] return string.Format("mongodb://{0}{1}/{2}{3}?{4}", authentication, host, database, options); } public static string ConnectionString() { return ConnectionString(null); } #endregion #region Public Properties public IMongoCollection<TEntity> Table { get { using (var mongo = Mongo.Create(ConnectionString())) { return mongo.Database.GetCollection<TEntity>(typeof(TEntity).Name); } } } #endregion #region IRepository<TEntity> 成員 public void SetDbContext(IUnitOfWork unitOfWork) { throw new NotImplementedException(); } public void Insert(TEntity item) { using (var mongo = Mongo.Create(ConnectionString())) { var table = mongo.Database.GetCollection<TEntity>(typeof(TEntity).Name); table.Insert(item); } } public void Delete(TEntity item) { using (var mongo = Mongo.Create(ConnectionString())) { var table = mongo.Database.GetCollection<TEntity>(typeof(TEntity).Name); table.Delete(item); } } public void Update(TEntity item) { using (var mongo = Mongo.Create(ConnectionString())) { var table = mongo.Database.GetCollection<TEntity>(typeof(TEntity).Name); table.Save(item); } } public IQueryable<TEntity> GetModel() { using (var mongo = Mongo.Create(ConnectionString())) { return mongo.Database.GetCollection<TEntity>(typeof(TEntity).Name).AsQueryable(); } } public TEntity Find(params object[] id) { using (var mongo = Mongo.Create(ConnectionString()))
{
return mongo.Database
.GetCollection<TEntity>(typeof(TEntity).Name)
.Find(new { ID = new ObjectId(id[0].ToString()) })
.FirstOrDefault();
} } #endregion #region IExtensionRepository<TEntity> 成員 public void Insert(IEnumerable<TEntity> item) { using (var mongo = Mongo.Create(ConnectionString())) { var table = mongo.Database.GetCollection<TEntity>(typeof(TEntity).Name); item.ToList().ForEach(i => { table.Insert(i); }); } } public void Update(IEnumerable<TEntity> item) { using (var mongo = Mongo.Create(ConnectionString())) { var table = mongo.Database.GetCollection<TEntity>(typeof(TEntity).Name); item.ToList().ForEach(i => { table.Save(i); }); } } public void Delete(IEnumerable<TEntity> item) { using (var mongo = Mongo.Create(ConnectionString())) { var table = mongo.Database.GetCollection<TEntity>(typeof(TEntity).Name); item.ToList().ForEach(i => { table.Delete(i); }); } } public void Update<T>(System.Linq.Expressions.Expression<Action<T>> entity) where T : class { throw new NotImplementedException(); } public IQueryable<TEntity> GetModel(System.Linq.Expressions.Expression<Func<TEntity, bool>> predicate) { using (var mongo = Mongo.Create(ConnectionString())) { return mongo.Database.GetCollection<TEntity>(typeof(TEntity).Name).AsQueryable().Where(predicate); } } public TEntity Find(System.Linq.Expressions.Expression<Func<TEntity, bool>> predicate) { using (var mongo = Mongo.Create(ConnectionString())) { return mongo.Database.GetCollection<TEntity>(typeof(TEntity).Name).AsQueryable().FirstOrDefault(predicate); } } public void BulkInsert(IEnumerable<TEntity> item, bool isRemoveIdentity) { throw new NotImplementedException(); } public void BulkInsert(IEnumerable<TEntity> item) { throw new NotImplementedException(); } public void BulkUpdate(IEnumerable<TEntity> item, params string[] fieldParams) { throw new NotImplementedException(); } public void BulkDelete(IEnumerable<TEntity> item) { throw new NotImplementedException(); } public event Action<SavedEventArgs> AfterSaved; public event Action<SavedEventArgs> BeforeSaved; public IQueryable<TEntity> GetModel(Frameworks.Entity.Core.Specification.ISpecification<TEntity> specification) { throw new NotImplementedException(); } public TEntity Find(Frameworks.Entity.Core.Specification.ISpecification<TEntity> specification) { return GetModel(specification).FirstOrDefault(); } public IQueryable<TEntity> GetModel(Action<IOrderable<TEntity>> orderBy, Frameworks.Entity.Core.Specification.ISpecification<TEntity> specification) { var linq = new Orderable<TEntity>(GetModel(specification)); orderBy(linq); return linq.Queryable; } #endregion #region IRepositoryAsync<TEntity> 成員 public Task InsertAsync(TEntity item) { throw new NotImplementedException(); } public Task DeleteAsync(TEntity item) { throw new NotImplementedException(); } public Task UpdateAsync(TEntity item) { throw new NotImplementedException(); } public Task InsertAsync(IEnumerable<TEntity> item) { throw new NotImplementedException(); } public Task UpdateAsync(IEnumerable<TEntity> item) { throw new NotImplementedException(); } public Task DeleteAsync(IEnumerable<TEntity> item) { throw new NotImplementedException(); } public Task BulkInsertAsync(IEnumerable<TEntity> item, bool isRemoveIdentity) { throw new NotImplementedException(); } public Task BulkInsertAsync(IEnumerable<TEntity> item) { throw new NotImplementedException(); } public Task BulkUpdateAsync(IEnumerable<TEntity> item, params string[] fieldParams) { throw new NotImplementedException(); } public Task BulkDeleteAsync(IEnumerable<TEntity> item) { throw new NotImplementedException(); } #endregion #region IOrderableRepository<TEntity> 成員 public IQueryable<TEntity> GetModel(Action<IOrderable<TEntity>> orderBy) { var linq = new Orderable<TEntity>(GetModel()); orderBy(linq); return linq.Queryable; } public IQueryable<TEntity> GetModel(Action<IOrderable<TEntity>> orderBy, System.Linq.Expressions.Expression<Func<TEntity, bool>> predicate) { var linq = new Orderable<TEntity>(GetModel(predicate)); orderBy(linq); return linq.Queryable; } #endregion } }