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

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

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

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

  <connectionStrings>
    <add name="NormTests" connectionString="mongodb://Username:[email protected]server:port/dbName/query"/>
  </connectionStrings>

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

  <appSettings file="config.user">
    <add key="host" value="localhost:27017"/>
    <add key="dbName" value=""/>
    <add key="userName" value=""/>
    <add key="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:[email protected]]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).FindOne(id);
            }
        }

        #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
    }
}
时间: 2024-10-27 17:43:34

MongoDB学习笔记~MongoDBRepository仓储的实现的相关文章

MongoDB学习笔记系列

回到占占推荐博客索引 该来的总会来的,Ef,Redis,MVC甚至Sqlserver都有了自己的系列,MongoDB没有理由不去整理一下,这个系列都是平时在项目开发时总结出来的,希望可以为各位一些帮助和启发,文章中有对新技术的研究(Mongo驱动),对老技术的回顾(代码重构),还有对架构设计的阐述等(面向接口编程,对扩展开放,对修改关闭,所以出现了IMongoRepository接口). MongoDB学习笔记系列~目录 MongoDB学习笔记~环境搭建 (2015-03-30 10:34) M

MongoDB学习笔记一:MongoDB的下载和安装

趁着这几天比较空闲,准备学习一下MongoDB数据库,今天就简单的学习了一些MongoDB的下载和安装,并创建了存储MongoDB的数据仓库.将自己今天学习到的写成博客分享给大家. 一.MongoDB的下载和安装 MongoDB的下载地址为:http://www.mongodb.org/ 1.进入官网的首页后,在首页的右上方单击Downloads连接,如图所示: 2.在页面中可以看到目前最新的版本和以前发布过的版本,这里选择最新版本,windows 32位的进行下载,文件的格式为ZIP格式的,单

MongoDB学习笔记(一:安装时出现The default storage engine &#39;wiredTiger&#39; is not available问题解决)

今晚在自己老式笔记本来试了一下MongoDB的安装,由于配置比较低,只能选择32位版本的MongoDB进行安装,在安装过程中碰到了上述标题所示错误,自己也捣鼓了一个小时左右,终于在一篇博客中找到答案,具体原文链接如下:http://blog.csdn.net/u013457382/article/details/50775268 MongoDB学习笔记(一:安装时出现The default storage engine 'wiredTiger' is not available问题解决)

Mongodb学习笔记

总结下这几天Mongodb学习笔记 /** * 获取MongoClient * @author xuyw * @email [email protected] * @param host * @param port * @return */ public static MongoClient getMongoClient(String host, int... port) { MongoClient mongoClient = null; int portlen = 0; try { if (p

[Spring Data MongoDB]学习笔记--建立数据库的连接

1. 有了上一篇的Mongo后,连接数据库我们还需要更多的信息,比如数据库名字,用户名和密码等. 我们可以继续来配置MongoDbFactory的实例. public interface MongoDbFactory { DB getDb() throws DataAccessException; DB getDb(String dbName) throws DataAccessException; } 然后我们可以继续用MongoDbFactory来创建MongoTemplate的实例. pu

mongodb学习笔记系列一

一.简介和安装 ./bin/mongod --dbpath /path/to/database --logpath /path/to/log --fork --port 27017 mongodb非常的占磁盘空间, 刚启动后要占3-4G左右,--smallfiles 二.基本命令 1.登录mongodb client /use/local/mongo 2.查看当前数据库 show databases; show dbs; 两个可能 3.admin是和管理有关的库,local 是放schema有关

[Spring Data MongoDB]学习笔记--牛逼的MongoTemplate

MongoTemplate是数据库和代码之间的接口,对数据库的操作都在它里面. 注:MongoTemplate是线程安全的. MongoTemplate实现了interface MongoOperations,一般推荐使用MongoOperations来进行相关的操作. MongoOperations mongoOps = new MongoTemplate(new SimpleMongoDbFactory(new Mongo(), "database")); MongoDB docu

[Spring Data MongoDB]学习笔记--注册一个Mongo实例

1. 通过Java based bean metadata @Configuration public class AppConfig { public @Bean Mongo mongo() throws UnknownHostExceptioin { return new Mongo("localhost"); } } 上面的方式包含异常处理,这并不是我们想要的. 所以,应该尽量用下面这种方式MongoFactoryBean,或者后面的xml方式. @Configuration p

MongoDB 学习笔记(二) 之查询

最简单的查询 个人认为mongoDB是面向对象的吧. 例如最简单的查询  整个数据集只有三条数据 第一查询姓名为张三的  数据 查询的条件比较好写 随意   db.collection.find(查询条件)   例如 15 得到的结果是这样 如果你不想返回某个字段呢 ,你可以自己定义返回的字段值 语法这样 db.collection.find({查询条件},{返回字段}) 16 我们看到每次查询 "_id" 这个字段 都返回  我们可以将它设置为0 这样的话就不会返回 如 查询条件里的