本人系新接觸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)
