回到目录

仓储大叔,只要是持久化的东西,都要把它和仓储撤上关系,为啥,为的是开发人员在使用时统一,高可用及方便在各种方式之间实现动态的切换,如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仓储的实现的更多相关文章

  1. MongoDB学习笔记系列

    回到占占推荐博客索引 该来的总会来的,Ef,Redis,MVC甚至Sqlserver都有了自己的系列,MongoDB没有理由不去整理一下,这个系列都是平时在项目开发时总结出来的,希望可以为各位一些帮助 ...

  2. MongoDB学习笔记系列~目录

    MongoDB学习笔记~环境搭建 (2015-03-30 10:34) MongoDB学习笔记~MongoDBRepository仓储的实现 (2015-04-08 12:00) MongoDB学习笔 ...

  3. PHP操作MongoDB学习笔记

    <?php/*** PHP操作MongoDB学习笔记*///*************************//**   连接MongoDB数据库  **////*************** ...

  4. MongoDB 学习笔记(原创)

    MongoDB 学习笔记 mongodb 数据库 nosql 一.数据库的基本概念及操作 SQL术语/概念 MongoDB术语/概念 解释/说明 database database 数据库 table ...

  5. mongoDB 学习笔记纯干货(mongoose、增删改查、聚合、索引、连接、备份与恢复、监控等等)

    最后更新时间:2017-07-13 11:10:49 原始文章链接:http://www.lovebxm.com/2017/07/13/mongodb_primer/ MongoDB - 简介 官网: ...

  6. MongoDB学习笔记(转)

    MongoDB学习笔记(一) MongoDB介绍及安装MongoDB学习笔记(二) 通过samus驱动实现基本数据操作MongoDB学习笔记(三) 在MVC模式下通过Jqgrid表格操作MongoDB ...

  7. 【转】MongoDB学习笔记(查询)

    原文地址 MongoDB学习笔记(查询) 基本查询: 构造查询数据. > db.test.findOne() { "_id" : ObjectId("4fd58ec ...

  8. MongoDB学习笔记(六)--复制集+sharding分片 && 总结

    复制集+sharding分片                                                               背景 主机 IP 服务及端口 Server A ...

  9. MongoDB学习笔记(五)--复制集 && sharding分片

    主从复制                                                                                       主从节点开启 主节 ...

随机推荐

  1. Node.js、express、mongodb 实现分页查询、条件搜索

    前言 在上一篇Node.js.express.mongodb 入门(基于easyui datagrid增删改查) 的基础上实现了分页查询.带条件搜索. 实现效果 1.列表第一页. 2.列表第二页 3. ...

  2. MongoDB性能优化

    一.索引 MongoDB 提供了多样性的索引支持,索引信息被保存在system.indexes 中,且默认总是为_id创建索引,它的索引使用基本和MySQL 等关系型数据库一样.其实可以这样说说,索引 ...

  3. C#利用反射+特性实现简单的实体映射数据库操作类

    附上源代码: using System; using System.Collections.Generic; using System.Data; using System.Linq; using S ...

  4. disabled="true" 的标签元素不可提交

    把jsp页面的input 标签设置成不可编辑: <input  name="Id"    value="${order.Id}" readOnly=&qu ...

  5. Socket编程——客户端,服务器端的读写操作

    URL网络编程,最大的特征就是一对一的响应! 1:客户端“写”,服务器端用于“读” package coreBookSocket2; import java.io.InputStreamReader; ...

  6. Linux下Redis的安装与配置

    redis是当前比较热门的NOSQL系统之一,它是一个key-value存储系统.和Memcached类似,但很大程度补偿了 memcached的不足,它支持存储的value类型相对更多,包括stri ...

  7. Lind.DDD.Manager里的3,7,15,31,63,127,255,511,1023,2047

    回到目录 进制 我是一个程序猿,我喜欢简单的数字,十进制如何,数字太多,有10种数字组成,但由于它广为人知,所有使用最为广泛,人们的惯性思维培养了十进制,并说它是最容易被计算的数字,事实上,在计算机里 ...

  8. Effective C#中文版

    我看的书是<Effective C#中文版——改善C#程序的50种方法>,Bill Wagner著,李建忠译.书比较老了,04年写的,主要针对C#1.0,但我相信其中的观点现在仍有价值.( ...

  9. 转载:C#中的泛型

    泛型(generic)是C#语言2.0和通用语言运行时(CLR)的一个新特性.泛型为.NET框架引入了类型参数(type parameters)的概念.类型参数使得设计类和方法时,不必确定一个或多个具 ...

  10. Java设计模式之单例模式

    很多人都疑惑,单例模式是什么?为什么要用单例模式?在这里,笔者记录的仅仅只是自己对于知识点的理解,如果有错误的,请下方评论指教,共同进步,谢谢. 单例模式是什么? 简单理解: 单例就是一个实例被多个用 ...