asp.net mvc Repository模式

來源:互聯網
上載者:User

近來發現很多ASP.NET MVC的例子中都使用了Repository模式,比如Oxite,ScottGu最近發布的免費的ASP.NET MVC教程都使用了該模式。就簡單看了下。

在《企業架構模式》中,譯者將Repository翻譯為資產庫。給出如下說明:
通過用來訪問領域對象的一個類似集合的介面,在領域與資料對應層之間進行協調。

在《領域驅動設計:軟體核心複雜性應對之道》中,譯者將Repository翻譯為倉儲,給出如下說明:
一種用來封裝儲存,讀取和尋找行為的機制,它類比了一個對象集合。

使用該模式的最大好處就是將領域模型從客戶代碼和資料對應層之間解耦出來。

我們來看下在LinqToSql中如何應用該模式。
1. 我們將對實體的公用操作部分,提取為IRepository介面,比如常見的增加,刪除等方法。如下代碼:

interface IRepository<T> where T : class{    IEnumerable<T> FindAll(Func<T, bool> exp);    void Add(T entity);    void Delete(T entity);    void Save();}

2.下面我們實現一個泛型的類來具體實現上面的介面的方法。

public class Repository<T> : IRepository<T> where T : class{    public DataContext context;    public Repository(DataContext context)    {        this.context = context;    }    public IEnumerable<T> FindAll(Func<T, bool> exp)    {        return context.GetTable<T>().Where(exp);    }    public void Add(T entity)    {        context.GetTable<T>().InsertOnSubmit(entity);    }    public void Delete(T entity)    {        context.GetTable<T>().DeleteOnSubmit(entity);    }    public void Save()    {        context.SubmitChanges();    }}

3.上面我們實現是每個實體公用的操作,但是實際中每個實體都有符合自己業務的邏輯。我們單獨定義另外一個介面,例如:

interface IBookRepository : IRepository<Book>{    IList<Book> GetAllByBookId(int id);}

4.最後該實體的Repository類實現如下:

public class BookRepository : Repository<Book>, IBookRepository{    public BookRepository(DataContext dc)        : base(dc)    { }    public IList<Book> GetAllByBookId(int id)    {        var listbook = from c in context.GetTable<Book>()                       where c.BookId == id                       select c;        return listbook.ToList();    }} 

上面只是為大家提供了一個最基本使用架構。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.