2012-12-09 39 views
3

今天我想實現數據庫連接的存儲庫模式+工作模式單元。我的代碼是否正確?因爲這是我第一個實現數據庫連接的工作單元。存儲庫使用MVC應用程序中的數據庫的UnitOfWork模式

一庫:

public class NotesRepository : INotesRepository 
{ 
    private DatabaseContext context; 

    public NotesRepository(DatabaseContext context) 
    { 
     this.context = context; 
    } 

    public IQueryable<Notes> GetAllNotes() 
    { 
     return (from x in context.Notes 
       select x); 
    } 
} 

二庫:

public class UnitOfWork 
{ 
    private DatabaseContext context = new DatabaseContext(); 
    private INotesRepository notesRepository; 
    private ICommentsRepository commentsRepository; 

    public INotesRepository NotesRepository 
    { 
     get 
     { 
      if (this.notesRepository == null) 
      { 
       this.notesRepository = new NotesRepository(context); 
      } 
      return notesRepository; 
     } 
    } 

    public ICommentsRepository CommentsRepository 
    { 
     get 
     { 
      if (this.commentsRepository == null) 
      { 
       this.commentsRepository = new CommentsRepository(context); 
      } 
      return commentsRepository; 
     } 
    } 
} 

和控制器中,我可以使用單多庫:

public class CommentsRepository : ICommentsRepository 
{ 
    private DatabaseContext context; 

    public CommentsRepository(DatabaseContext context) 
    { 
     this.context = context; 
    } 

    public IQueryable<Comments> GetAllComments() 
    { 
     return (from x in context.Comments 
       select x); 
    } 
} 

數據庫連接工作類單位數據庫連接:

public class HomeController : Controller 
    { 
     private UnitOfWork unitOfWork = new UnitOfWork();   

     public ViewResult Index() 
     { 
      var a = unitOfWork.NotesRepository.GetAllNotes(); 
      var b = unitOfWork.CommentsRepository.GetAllComments(); 

      return View(); 
     } 
    } 

回答

1

你的實現是非常正確的:)

但我建議你用IUnitOfWork接口並通過DatabaseContext實例在構造函數中。

另一件要做的事情是在UnitOfWork中創建一個SaveChanges方法來將數據提交到數據庫。

+0

好thx非常多:) – michael

+0

不客氣:) –

相關問題