3

今日は、データベース接続用のリポジトリパターン+作業単位パターンを実装したいと思います。以下の私のコードは正しいですか?これは、データベース接続の最初の実装作業単位だからです。

最初のリポジトリ:

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();
        }
    }
4

1 に答える 1

1

Your implementation is very right :)

But I advice you to use IUnitOfWork interface and pass the DatabaseContext instance in the constructor.

Another thing to do is to make a SaveChanges method in the UnitOfWork to commit the data to the database.

于 2012-12-09T09:54:36.263 に答える