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分片
主从复制 主从节点开启 主节 ...
随机推荐
- Oracle常用的SQL方法总结
在项目中一般需要对一些数据进行处理,以下提供一些基本的SQL语句: 1.基于条件的插入和修改:需要在表中插入一条记录,插入前根据key标识判断.如果标识符不存在,则插入新纪录,如果标识符存在,则根据语 ...
- 你的日志组件记录够清晰嘛?--自己开发日志组件 Logger
现在现成的日志组件实在是太多太多,为什么我还需要自己实现呢????? 需求来源于java的log4j, [07-31 16:40:00:557:WARN : com.game.engine.threa ...
- CSS魔法堂:重拾Border之——不仅仅是圆角
前言 当CSS3推出border-radius属性时我们是那么欣喜若狂啊,一想到终于不用再添加额外元素来模拟圆角了,但发现border-radius还分水平半径和垂直半径,然后又发现border-t ...
- ASP.NET MVC 之自定义HtmlHelper
前言 HtmlHelper方法为我们提供很多html标签,只需在页面调用就行了,但是微软并没有把所有的html标签都对应有了扩展方法,需要我们重新自定义HtmlHelper,来满足我们需要. 方法 如 ...
- html5数字和颜色输入框
html5功能强大,数字和颜色输入框例子 效果:http://hovertree.com/code/html5/rxujb6g8.htm <!DOCTYPE html> <html& ...
- Android Permission 访问权限大全(转)
程序执行需要读取到安全敏感项必需在androidmanifest.xml中声明相关权限请求, 完整列表如下: android.permission.ACCESS_CHECKIN_PROPERTIES允 ...
- 背水一战 Windows 10 (29) - 控件(文本类): RichTextBlock, RichTextBlockOverflow, RichEditBox
[源码下载] 背水一战 Windows 10 (29) - 控件(文本类): RichTextBlock, RichTextBlockOverflow, RichEditBox 作者:webabcd ...
- N皇后问题
题目描述 在n×n格的棋盘上放置彼此不受攻击的n个皇后.按照国际象棋的规则,皇后可以攻击与之处在同一行或同一列或同一斜线上的棋子.n后问题等价于再n×n的棋盘上放置n个后,任何2个皇后不妨在同一行或同 ...
- Oracle账户解锁/锁定
1. 首先用系统账号登录: sqlplus /nolog conn /as sysdba 2. 输入命令对账户解锁/锁定: ALTER USER scott ACCOUNT UNLOCK ALTER ...
- spring入门(六)【springMVC中各数据源配置】
在使用spring进行javaWeb开发的过程中,需要和数据库进行数据交换,为此要经常获取数据库连接,使用JDBC的方式获取数据库连接,使用完毕之后再释放连接,这种过程对系统资源的消耗无疑是很大的,这 ...