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

本文涉及的产品
云数据库 MongoDB,独享型 2核8GB
推荐场景:
构建全方位客户视图
简介:

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

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

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

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

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

  <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>

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

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

下面看一下源代码

namespace MongoDb.Data.Core
{
    /// <summary>
    /// 通过MongoDb实现数据的持久化
    /// </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 } }

 本文转自博客园张占岭(仓储大叔)的博客,原文链接:MongoDB学习笔记~MongoDBRepository仓储的实现,如需转载请自行联系原博主。

目录
相关文章
|
存储 监控 NoSQL
MongoDB 快速入门-MongoDB 最佳实践(二)|学习笔记
快速学习 MongoDB 快速入门-MongoDB 最佳实践(二)
603 0
MongoDB 快速入门-MongoDB 最佳实践(二)|学习笔记
|
存储 JSON NoSQL
【BackEnd--Mongodb】学习笔记(完整详细版)
MongoDB是一种面向文档的非关系型数据库,所谓的面向文档是一种类似JSON的结构,因此可以简单理解MongoDB存储的是各种各样的JSONMongoDB可以快速开发web型应用,因为存储的是JSON格式,因此无需像关系型数据库那样需要建表,非常的的灵活。
452 0
|
NoSQL 关系型数据库 MySQL
|
存储 缓存 NoSQL
Spring Boot2.5 实战 MongoDB 与高并发 Redis 缓存|学习笔记
快速学习 Spring Boot2.5 实战 MongoDB 与高并发 Redis 缓存
Spring Boot2.5 实战 MongoDB 与高并发 Redis 缓存|学习笔记
|
存储 SQL JSON
走进 MongoDB|学习笔记
快速学习走进 MongoDB
310 0
走进 MongoDB|学习笔记
|
SQL 存储 分布式计算
MongoDB 聚合框架|学习笔记
快速学习 MongoDB 聚合框架
515 0
MongoDB 聚合框架|学习笔记
|
存储 JSON NoSQL
MongoDB 简介&amp;体系结构&amp;数据模型&amp; | 学习笔记
快速学习 MongoDB简介&amp;体系结构&amp;数据模型&amp;
244 0
MongoDB 简介&amp;体系结构&amp;数据模型&amp; | 学习笔记
|
NoSQL 算法 Linux
MongoDB学习笔记(五) 集群搭建之副本集
MongoDB学习笔记(五) 集群搭建之副本集
558 0
|
NoSQL Linux MongoDB
MongoDB学习笔记(四) 集群搭建之主从复制
MongoDB学习笔记(四) 集群搭建之主从复制
741 0
|
分布式计算 NoSQL MongoDB
MongoDB学习笔记(三) 聚合
MongoDB学习笔记(三) 聚合
225 0

推荐镜像

更多