回到目录

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

    上一篇讲的是单向多对一的表关系,与单向一对多的关系正好相反,如下图所示关系: ,可以看出年级表和学生表是一对多的关系,一条年级信息对应多条学生信息,在hibernate中成为单向的一对多的映射关系,应 ...

  2. 原创:经验分享:微信小程序外包接单常见问题及流程

    从九月底内测到现在已经三个半月.凌晨一点睡觉已经习以为常,也正是这样,才让无前端经验的我做微信小程序开发并不感到费劲.最近才开始接微信小程序的外包项目,目前已经签下了五份合同,成品出了两个.加上转给朋 ...

  3. WebGIS中矢量切图的初步研究

    文章版权由作者李晓晖和博客园共有,若转载请于明显处标明出处:http://www.cnblogs.com/naaoveGIS/. 1.背景 在GIS领域,金字塔技术一直是一个基础性技术,WMTS规范专 ...

  4. Sql Server 聚集索引扫描 Scan Direction的两种方式------FORWARD 和 BACKWARD

    最近发现一个分页查询存储过程中的的一个SQL语句,当聚集索引列的排序方式不同的时候,效率差别达到数十倍,让我感到非常吃惊 由此引发出来分页查询的情况下对大表做Clustered Scan的时候, 不同 ...

  5. android获得ImageView图片的等级

    android获得ImageView图片的等级问题 要实现的功能如下图,点击分享能显示选中与不选中状态,然后发送是根据状态来实现具体分享功能. 在gridview中有5个子项,每个子元素都有两张图片A ...

  6. 详解PHP输入流php://input

    在使用xml-rpc的时候,server端获取client数据,主要是通过php输入流input,而不是$_POST数组.所以,这里主要探讨php输入流php://input 对一php://inpu ...

  7. 我的angularjs源码学习之旅1——初识angularjs

    angular诞生有好几年光景了,有Google公司的支持版本更新还是比较快,从一开始就是一个热门技术,但是本人近期才开始接触到.只能感慨自己学习起点有点晚了.只能是加倍努力赶上技术前线. 因为有分析 ...

  8. MapReduce 单词统计案例编程

    MapReduce 单词统计案例编程 一.在Linux环境安装Eclipse软件 1.   解压tar包 下载安装包eclipse-jee-kepler-SR1-linux-gtk-x86_64.ta ...

  9. HTML5填充颜色的fillStyle测试

    效果:http://hovertree.com/texiao/html5/canvas/1/ 代码: <html> <head> <meta http-equiv=&qu ...

  10. 墙裂推荐4款js网页烟花特效

    以下是几款网页特效和一款软件: http://keleyi.com/keleyi/phtml/jstexiao/1.htm  http://keleyi.com/keleyi/phtml/jstexi ...