2012-12-09 37 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

不客气:) –

相关问题