MongoDB:利用官方驱动改装为EF代码风格的MongoDB.Repository框架 一

本人系新接触MongoDB不久,属于MongoDB的菜鸟范畴。在使用MongoDB的过程中,总结了一些认识,在此总结跟大家分享。欢迎拍砖。

关于MongoDB的内容,在此就不做介绍了,网上有浩如烟海的文章介绍。本人不善理论,不妥之处,望指正。

想法来由:本人之前主要使用EF的CodeFirst方式做一些开发,EF的优劣在此不做评述。但已经习惯了EF式的代码编写方式,所以做了一个小的框架,来模拟实现类似EF代码风格,以减少开发者在实际使用过程中对MongoDB的关注和维护。为其取名为MongoDB.Repository。

中心思想:在使用的过程中不必关心任何的MongoDB的内容。

在此先介绍一下MongoDB.Repository的使用方式

使用过EF的朋友应该比较熟悉EF的风格,DBContext和ModelDesign是EF的主要构成部分,在此我也设计了一个IMongoDBContext和IEntity两个接口,

    public interface IMongoDBContext
{
/// <summary>
/// register entity type
/// </summary>
/// <param name="registration"></param>
void OnRegisterModel(ITypeRegistration registration); /// <summary>
/// name of ConnectionString in config file
/// </summary>
string ConnectionStringName { get; } /// <summary>
/// build Configuration by config file
/// </summary>
/// <returns></returns>
IConfigurationRegistration BuildConfiguration();
}
public interface IEntity
{
/// <summary>
/// mongo id
/// </summary>
string Id { get; set; }
/// <summary>
/// save document
/// </summary>
void Save();
/// <summary>
/// remove document
/// </summary>
void Remove();
}

  IMongoDBContext为上下文,在该上下文中必须实现OnRegisterModel方法,以注册需要在框架中使用的模型,未注册的模型将不会在MongoDB中体现,以免MongoDB的Collection出现无法控制的局面。IEntity为具体的实例接口,定义的model均需继承该接口。该接口提供了Save和Remove方法,以方便的保存和删除。为了方便使用,框架提供了针对于上述两个接口的抽象实现MongoDBContext和Entity。

  在使用时,只需先注册当前上下文,再注册需要维护的CollectionType,后面即可以Entity.Save()的方式操作数据库。

  下面给出实操代码:

    public class Student : Entity
{
public string Name { get; set; }
public int Age { get; set; }
}
public class TestDBContext : MongoDBContext
{
    //TestDBContext即配置文件中的节点的名称
public TestDBContext() : base("TestDBContext") { } public override void OnRegisterModel(ITypeRegistration registration)
{
registration.RegisterType<Student>();//在上下文中注册可用的实例
}
}
public void Setup()
{
MongoDBRepository.RegisterMongoDBContext(new TestDBContext());//注册上下文
Student student = new Student();
student.Name = "hyf";
student.Age = 30;
student.Save();//保存当前实例到数据库
student.Remove()//删除当前实例
}

  配置文件如下:

  <connectionStrings>
<add name="TestDBContext" connectionString="mongodb://localhost:27017/TestMongo"/>
</connectionStrings>

  如上,除了Save和Remove,还有就是Get和Select。框架提供了一些查询的扩展方法,使用如下:

    //获取实例
var stud = Entity.Get<Student>(student.Id);
  var stud = Entity.Get<Student>(s=>s.Age=="hyf");
//分页查询
var querable = Entity.Select<Student>(s => s.Age >= 19 && s.Age <= 22, s => s.Age, 1, 2, out pageCount, out allCount).ToList(); //批量删除
Entity.RemoveAll<Student>(e => e.Name == "hyf"); //批量保存
Entity.Save(new List<Student>() {
new Student{ Name="hyf", Age=33 },
new Student{ Name="zhc", Age=30 }
});

  通过以上操作,可以完成一些简单CURD操作,甚至构建一个简单的系统应用。

  在使用中,只需在config中配置MongoDB即可,其余关于MongoDB的任何内容不用关心。

  这只是本人对MongoDB的一些初探,源码并没有任何的技术含量,欢迎大家拍砖并提出更好的设计理念。

  源码地址  (源码基于MongoDB的官方驱动,VS2012开发,源码已经提交至github)

  

上一篇:ifram 实现左侧菜单,右侧显示内容


下一篇:ExtPB.Net:窗体应用技巧(2)在树形导航下打开弹出的win窗口