适用于 RavenDB 的抽象泛型 DAO
适用于 RavenDB 的抽象和泛型 DAO
引言
在本文中,我将通过代码示例向您展示如何为 Raven DB 构建一个抽象 DAO(数据访问对象)。
有时您希望对 RavenDB 实体执行 CRUD 操作,在这种情况下,使用可重用的泛型对象来简化重复性工作会是一个好主意。 是的,这正是我们需要创建一个辅助类或抽象 DAO 来执行所有重复性任务的原因。
如果您想知道您希望对实体执行哪些类型的操作,以下是一些常用的操作。
Get
– 通过 ID 获取文档。GetAll
- 获取所有文档。GetPagedList
– 获取分页文档列表。GetDocumentStore
– 获取文档存储。内存 vs 真实数据库。Save
– 持久化文档。Delete
– 删除文档。
注意 – 我们使用文档存储在默认数据库上打开会话,以便在 RavenDB 上执行数据库操作。
背景
需要对 NoSQL 数据库有一定的了解和工作经验。
使用代码
以下是构建适用于 RavenDB 的抽象 DAO 的代码示例。
/// <summary> /// Abstract DAO for RavenDB /// </summary> /// <typeparam name="T">T is an generic RavenDB Entity</typeparam> public abstract class Dao<T> { string _database = ""; bool _inMemory = false; public Dao(string database, bool inMemory = false) { _database = database; _inMemory = inMemory; } public IDocumentStore GetDocumentStore() { if (_inMemory) return DocumentStoreHolder.GetInMemoryStore(); return DocumentStoreHolder.GetStore(); } public virtual T Get(string id) { using (var documentStore = GetDocumentStore()) { using (var session = documentStore.OpenSession(_database)) { return session.Load<T>(id); } } } public virtual List<T> GetAll() { using (var documentStore = GetDocumentStore()) { using (var session = documentStore.OpenSession(_database)) { return session.Query<T>().ToList(); } } } public List<T> GetPagedList(int startingPageIndex, int pageSize) { using (var documentStore = GetDocumentStore()) { using (IDocumentSession session = documentStore.OpenSession(_database)) { return session.Query<T>() .Take(pageSize) .Skip(startingPageIndex * pageSize) .ToList(); } } } public virtual void Save(T entity) { using (var documentStore = GetDocumentStore()) { using (var session = documentStore.OpenSession(_database)) { session.Store(entity); session.SaveChanges(); // Save all pending changes to server } } } public virtual void Delete(string id) { using (var documentStore = GetDocumentStore()) { using (var session = documentStore.OpenSession(_database)) { T entity = session.Load<T>(id); session.Delete(entity); session.SaveChanges(); } } } }
以下代码只是一个示例,用于展示抽象 DAO 的用法。 我们通过扩展具有特定类型(即“Company
”)的泛型 DAO 来构建一个“CompanyDao
”。
public class CompanyDao : Dao<Company> { public CompanyDao(string database, bool inMemory = false) : base(database, inMemory) { } }
以下是调用“CompanyDao
”的代码片段。
void SaveCompanyInfo() { var company = new Company { ExternalId = "ALFKI", Name = "Alfreds Futterkiste", Contact = new Contact { Name = "Maria Anders", Title = "Sales Representative" }, Address = new Address { Line1 = "Obere Str. 57", Line2 = "Zip 12345", City = "Berlin", Region = null, PostalCode = 12209, Country = "Germany" }, Phone = "030-0074321", Fax = "030-0076545" }; var companyDao = new CompanyDao(DATABASE, inMemory); companyDao.Save(company); }
关注点
我一直在玩一些新技术:)
历史
版本 1.0 - 发布初始版本 02/26/2016。