今日は、データベース接続用のリポジトリパターン+作業単位パターンを実装したいと思います。以下の私のコードは正しいですか?これは、データベース接続の最初の実装作業単位だからです。
最初のリポジトリ:
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);
}
}
2番目のリポジトリ:
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 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 HomeController : Controller
{
private UnitOfWork unitOfWork = new UnitOfWork();
public ViewResult Index()
{
var a = unitOfWork.NotesRepository.GetAllNotes();
var b = unitOfWork.CommentsRepository.GetAllComments();
return View();
}
}