设为首页 收藏本站
查看: 1450|回复: 0

[经验分享] MongoDB学习笔记~MongoDBRepository仓储的实现

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2015-7-6 11:24:37 | 显示全部楼层 |阅读模式
  回到目录
  仓储大叔,只要是持久化的东西,都要把它和仓储撤上关系,为啥,为的是开发人员在使用时统一,高可用及方便在各种方式之间实现动态的切换,如ef与redis和mongoDB的切换,你完成可以通过IRepository接口再配合IOC来实现,方便致极!
  之间写过一个redis仓储和xml仓储,感兴趣的同学可以先去看看,呵呵。
  MongoDB在实现仓储时,先要知道一些概念,即它的一些connectionstring,即连接串



  


  对于大叔的MongoDBRepository,把它进行了拆分,使用Appsetting进行分别的设置



  
  
   
   
   
  
  如果要配置读写分离,那么第一个host为主库,后面的为从库,如下面的字符串,将写操作定在主库,读操作定在各个从库



mongodb://server1,server2,server3/?slaveOk=true
  下面看一下源代码



namespace MongoDb.Data.Core
{
///
/// 通过MongoDb实现数据的持久化
///
///
public class MongoDBRepository :
IExtensionRepository 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 Table
{
get
{
using (var mongo = Mongo.Create(ConnectionString()))
{
return mongo.Database.GetCollection(typeof(TEntity).Name);
}
}
}
#endregion
#region IRepository 成员
public void SetDbContext(IUnitOfWork unitOfWork)
{
throw new NotImplementedException();
}
public void Insert(TEntity item)
{
using (var mongo = Mongo.Create(ConnectionString()))
{
var table = mongo.Database.GetCollection(typeof(TEntity).Name);
table.Insert(item);
}
}
public void Delete(TEntity item)
{
using (var mongo = Mongo.Create(ConnectionString()))
{
var table = mongo.Database.GetCollection(typeof(TEntity).Name);
table.Delete(item);
}
}
public void Update(TEntity item)
{
using (var mongo = Mongo.Create(ConnectionString()))
{
var table = mongo.Database.GetCollection(typeof(TEntity).Name);
table.Save(item);
}
}
public IQueryable GetModel()
{
using (var mongo = Mongo.Create(ConnectionString()))
{
return mongo.Database.GetCollection(typeof(TEntity).Name).AsQueryable();
}
}
public TEntity Find(params object[] id)
{
  using (var mongo = Mongo.Create(ConnectionString()))
             {
                return mongo.Database
                    .GetCollection(typeof(TEntity).Name)
                    .Find(new { ID = new ObjectId(id[0].ToString()) })
                    .FirstOrDefault();
             }
}
#endregion
#region IExtensionRepository 成员
public void Insert(IEnumerable item)
{
using (var mongo = Mongo.Create(ConnectionString()))
{
var table = mongo.Database.GetCollection(typeof(TEntity).Name);
item.ToList().ForEach(i =>
{
table.Insert(i);
});
}
}
public void Update(IEnumerable item)
{
using (var mongo = Mongo.Create(ConnectionString()))
{
var table = mongo.Database.GetCollection(typeof(TEntity).Name);
item.ToList().ForEach(i =>
{
table.Save(i);
});
}
}
public void Delete(IEnumerable item)
{
using (var mongo = Mongo.Create(ConnectionString()))
{
var table = mongo.Database.GetCollection(typeof(TEntity).Name);
item.ToList().ForEach(i =>
{
table.Delete(i);
});
}
}
public void Update(System.Linq.Expressions.Expression entity) where T : class
{
throw new NotImplementedException();
}
public IQueryable GetModel(System.Linq.Expressions.Expression predicate)
{
using (var mongo = Mongo.Create(ConnectionString()))
{
return mongo.Database.GetCollection(typeof(TEntity).Name).AsQueryable().Where(predicate);
}
}
public TEntity Find(System.Linq.Expressions.Expression predicate)
{
using (var mongo = Mongo.Create(ConnectionString()))
{
return mongo.Database.GetCollection(typeof(TEntity).Name).AsQueryable().FirstOrDefault(predicate);
}
}
public void BulkInsert(IEnumerable item, bool isRemoveIdentity)
{
throw new NotImplementedException();
}
public void BulkInsert(IEnumerable item)
{
throw new NotImplementedException();
}
public void BulkUpdate(IEnumerable item, params string[] fieldParams)
{
throw new NotImplementedException();
}
public void BulkDelete(IEnumerable item)
{
throw new NotImplementedException();
}
public event Action AfterSaved;
public event Action BeforeSaved;
public IQueryable GetModel(Frameworks.Entity.Core.Specification.ISpecification specification)
{
throw new NotImplementedException();
}
public TEntity Find(Frameworks.Entity.Core.Specification.ISpecification specification)
{
return GetModel(specification).FirstOrDefault();
}
public IQueryable GetModel(Action orderBy, Frameworks.Entity.Core.Specification.ISpecification specification)
{
var linq = new Orderable(GetModel(specification));
orderBy(linq);
return linq.Queryable;
}
#endregion
#region IRepositoryAsync 成员
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 item)
{
throw new NotImplementedException();
}
public Task UpdateAsync(IEnumerable item)
{
throw new NotImplementedException();
}
public Task DeleteAsync(IEnumerable item)
{
throw new NotImplementedException();
}
public Task BulkInsertAsync(IEnumerable item, bool isRemoveIdentity)
{
throw new NotImplementedException();
}
public Task BulkInsertAsync(IEnumerable item)
{
throw new NotImplementedException();
}
public Task BulkUpdateAsync(IEnumerable item, params string[] fieldParams)
{
throw new NotImplementedException();
}
public Task BulkDeleteAsync(IEnumerable item)
{
throw new NotImplementedException();
}
#endregion
#region IOrderableRepository 成员
public IQueryable GetModel(Action orderBy)
{
var linq = new Orderable(GetModel());
orderBy(linq);
return linq.Queryable;
}
public IQueryable GetModel(Action orderBy, System.Linq.Expressions.Expression predicate)
{
var linq = new Orderable(GetModel(predicate));
orderBy(linq);
return linq.Queryable;
}
#endregion
}
}
  回到目录

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-83786-1-1.html 上篇帖子: MongoDB 分片collection 唯一索引(_id键)的误区 下篇帖子: MongoDB-索引
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表