回到目录

仓储大叔,只要是持久化的东西,都要把它和仓储撤上关系,为啥,为的是开发人员在使用时统一,高可用及方便在各种方式之间实现动态的切换,如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. struts2学习笔记--使用struts2插件实现ajax处理(返回json数据)

    贴一个简单的例子,通过jquery的post调用action,定义一个对象User,有name和age属性,实例化几个对象,以json的格式返回到jsp,在前台页面显示出来,模拟用户列表. 导入相关j ...

  2. 关于replace()方法中第二个参数的转义问题

    如果你想通过Javascript代码在网页中呈现 \ 字符,则在JS代码中你必须输入两个反斜杠 \\,否则会报错.比如: var a = "\"; alert(a); //chro ...

  3. 【JS】heatmap.js v1.0 到 v2.0,详细总结一下:)

    前段时间,项目要开发热力图插件,研究了heatmap.js,打算好好总结一下. 本文主要有以下几部分内容: 部分源码理解 如何迁移到v2.0 v2.0官方文档译文 关于heatmap.js介绍,请看这 ...

  4. mysql小数格式化正确方法

    用到小数格式化,mysql了解很肤浅,只会简单的sql语句,于是百度,发现大家都是转载同一个文章,好无语. 而且,结果验证还是不正确,查了官方api,终于写出来了. 另外,还是保存下百度的几个方法: ...

  5. Html标签列表【转】

    Html标签 Html标签按功能类别排列 基础 标签 描述 <!DOCTYPE> 定义文档类型. <html> 定义 HTML 文档. <title> 定义文档的标 ...

  6. HTML基础知识汇总

    前言 一直想总结一下,苦于没有时间,正好看到了一个总结了不错的博客,我就在他的基础上进行一下测试并总结,原博地址:http://www.cnblogs.com/wanghzh/p/5805587.ht ...

  7. Nancy之基于Nancy.Owin的小Demo

    前面做了基于Nancy.Hosting.Aspnet和Nancy.Hosting.Self的小Demo 今天我们来做个基于Nancy.Owin的小Demo 开始之前我们来说说什么是Owin和Katan ...

  8. MSSQL 2012安装报错之0x858C001B

    之前安装 Microsoft Sql Server 2012 R2 的时候总是报这样的错误: SQL Server Setup has encountered the following error: ...

  9. 转载:《TypeScript 中文入门教程》 12、类型推导

    版权 文章转载自:https://github.com/zhongsp 建议您直接跳转到上面的网址查看最新版本. 介绍 这节介绍TypeScript里的类型推论.即,类型是在哪里如何被推断的. 基础 ...

  10. web前端--边框的特征

    1.一个面试题:边框是什么形状的? 你可能认为是一个矩形的  细心地人可能说是 梯形  或者 三角形 比较合理的答案是 非矩形的 2.画三角形 将div的width height 都设置为0px bo ...