public interface IMongoDBContext
{
///
/// register entity type
///
///
void OnRegisterModel(ITypeRegistration registration);
///
/// name of ConnectionString in config file
///
string ConnectionStringName { get; }
///
/// build Configuration by config file
///
///
IConfigurationRegistration BuildConfiguration();
}
public interface IEntity
{
///
/// mongo id
///
string Id { get; set; }
///
/// save document
///
void Save();
///
/// remove document
///
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();//在上下文中注册可用的实例
}
}
public void Setup()
{
MongoDBRepository.RegisterMongoDBContext(new TestDBContext());//注册上下文
Student student = new Student();
student.Name = "hyf";
student.Age = 30;
student.Save();//保存当前实例到数据库
student.Remove()//删除当前实例
}