Repository模式
近來發現很多ASP.NET MVC的例子中都使用了Repository模式,比如Oxite,ScottGu最近發布的免費的ASP.NET MVC教程都使用了該模式。就簡單看了下。
在《企業架構模式》中,譯者將Repository翻譯為資源庫。給出如下說明:
通過用來訪問領域對象的一個類似集合的接口,在領域與數據映射層之間進行協調。
在《領域驅動設計:軟件核心復雜性應對之道》中,譯者將Repository翻譯為倉儲,給出如下說明:
一種用來封裝存儲,讀取和查找行為的機制,它模擬了一個對象集合。
使用該模式的最大好處就是將領域模型從客戶代碼和數據映射層之間解耦出來。
我們來看下在LinqToSql中如何應用該模式。
1. 我們將對實體的公共操作部分,提取為IRepository接口,比如常見的增加,刪除等方法。如下代碼:
1 interface IRepository<T> where T : class 2 { 3 IEnumerable<T> FindAll(Func<T, bool> exp); 4 void Add(T entity); 5 void Delete(T entity); 6 void Save(); 7 }2.下面我們實現一個泛型的類來具體實現上面的接口的方法。
1 public class Repository<T> : IRepository<T> where T : class 2 { 3 public DataContext context; 4 public Repository(DataContext context) 5 { 6 this.context = context; 7 } 8 public IEnumerable<T> FindAll(Func<T, bool> exp) 9 { 10 return context.GetTable<T>().Where(exp); 11 } 12 public void Add(T entity) 13 { 14 context.GetTable<T>().InsertOnSubmit(entity); 15 } 16 public void Delete(T entity) 17 { 18 context.GetTable<T>().DeleteOnSubmit(entity); 19 } 20 public void Save() 21 { 22 context.SubmitChanges(); 23 } 24 }3.上面我們實現是每個實體公共的操作,但是實際中每個實體都有符合自己業務的邏輯。我們單獨定義另外一個接口,例如:
1 interface IBookRepository : IRepository<Book> 2 { 3 IList<Book> GetAllByBookId(int id); 4 }4.最后該實體的Repository類實現如下:
1 public class BookRepository : Repository<Book>, IBookRepository 2 { 3 public BookRepository(DataContext dc) 4 : base(dc) 5 { } 6 public IList<Book> GetAllByBookId(int id) 7 { 8 var listbook = from c in context.GetTable<Book>() 9 where c.BookId == id 10 select c; 11 return listbook.ToList(); 12 } 13 }上面只是為大家提供了一個最基本使用框架。
作者:生魚片
出處:http://carysun.cnblogs.com/
本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。
轉載于:https://www.cnblogs.com/duanyong/articles/4875798.html
總結
以上是生活随笔為你收集整理的Repository模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java基础知识强化之IO流笔记42:I
- 下一篇: oracle中的备注的配置与查询