MongoDB学习笔记~MongoDBRepository仓储的实现
仓储大叔,只要是持久化的东西,都要把它和仓储撤上关系,为啥,为的是开发人员在使用时统一,高可用及方便在各种方式之间实现动态的切换,如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仓储的实现的更多相关文章
- MongoDB学习笔记系列
回到占占推荐博客索引 该来的总会来的,Ef,Redis,MVC甚至Sqlserver都有了自己的系列,MongoDB没有理由不去整理一下,这个系列都是平时在项目开发时总结出来的,希望可以为各位一些帮助 ...
- MongoDB学习笔记系列~目录
MongoDB学习笔记~环境搭建 (2015-03-30 10:34) MongoDB学习笔记~MongoDBRepository仓储的实现 (2015-04-08 12:00) MongoDB学习笔 ...
- PHP操作MongoDB学习笔记
<?php/*** PHP操作MongoDB学习笔记*///*************************//** 连接MongoDB数据库 **////*************** ...
- MongoDB 学习笔记(原创)
MongoDB 学习笔记 mongodb 数据库 nosql 一.数据库的基本概念及操作 SQL术语/概念 MongoDB术语/概念 解释/说明 database database 数据库 table ...
- mongoDB 学习笔记纯干货(mongoose、增删改查、聚合、索引、连接、备份与恢复、监控等等)
最后更新时间:2017-07-13 11:10:49 原始文章链接:http://www.lovebxm.com/2017/07/13/mongodb_primer/ MongoDB - 简介 官网: ...
- MongoDB学习笔记(转)
MongoDB学习笔记(一) MongoDB介绍及安装MongoDB学习笔记(二) 通过samus驱动实现基本数据操作MongoDB学习笔记(三) 在MVC模式下通过Jqgrid表格操作MongoDB ...
- 【转】MongoDB学习笔记(查询)
原文地址 MongoDB学习笔记(查询) 基本查询: 构造查询数据. > db.test.findOne() { "_id" : ObjectId("4fd58ec ...
- MongoDB学习笔记(六)--复制集+sharding分片 && 总结
复制集+sharding分片 背景 主机 IP 服务及端口 Server A ...
- MongoDB学习笔记(五)--复制集 && sharding分片
主从复制 主从节点开启 主节 ...
随机推荐
- 1Z0-053 争议题目解析212
1Z0-053 争议题目解析212 考试科目:1Z0-053 题库版本:V13.02 题库中原题为: 212.Note the following parameters settings in you ...
- 初次使用AngularJS中的ng-view,路由控制
AngularJS中的route可以控制页面元素的改变,使多页面变成一个单页面 第一步:引入必要的js: <script src="js/lib/angular.js"> ...
- 如何设置 Panorama 控件的只读 SelectedIndex 属性?
在 OnNavigatedTo() 方法中设置: panoramaControl.DefaultItem = panoramaControl.Items[indexToSet];
- 进一步丰富和简化表单管理的组件:form.js
上文<简洁易用的表单数据设置和收集管理组件>介绍了我自己的表单管理的核心内容,本文在上文的基础上继续介绍自己关于表单初始值获取和设置以及表单数据提交等内容方面的做法,上文的组件粒度很小,都 ...
- C# decimal保留指定的小数位数,不四舍五入
decimal保留指定位数小数的时候,.NET自带的方法都是四舍五入的. 项目中遇到分摊金额的情况,最后一条的金额=总金额-已经分摊金额的和. 这样可能导致最后一条分摊的时候是负数,所以自己写了一个保 ...
- WinForm 窗体属性 窗体美化
WinForm是·Net开发平台中对Windows Form的一种称谓. Windows窗体的一些重要特点如下: 功能强大:Windows窗体可用于设计窗体和可视控件,以创建丰富的基于Windows的 ...
- 把cookie以json形式返回,用js来set cookie.(解决手机浏览器未知情况下获取不到cookie)
.继上一篇随笔,链接点我,解决手机端cookie的问题. .上次用cookie+redis实现了session,并且手机浏览器可能回传cookies有问题,所以最后用js取出cookie跟在请求的ur ...
- python编码规范
python编码规范 文件及目录规范 文件保存为 utf-8 格式. 程序首行必须为编码声明:# -*- coding:utf-8 -*- 文件名全部小写. 代码风格 空格 设置用空格符替换TAB符. ...
- jquery实现表格动态添加
//点击追加触发$(function(){$("#button").click(function(){var div_ = $("#sel").val();va ...
- php实现设计模式之 桥接模式
<?php /** 桥接模式:将抽象部分与实现部分分离,使它们都可以独立的变化. * * 在软件系统中,某些类型由于自身的逻辑,它具有两个或多个维度的变化,桥接模式就是应对这种多维度的变化 */ ...