3

Today I would like to implement repository pattern + unit of work pattern for database connection. Is my code bellow correct?? Because this is my first implementation unit of work for database connection.

First repository:

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

Second repository:

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

Unit of work class for database connection:

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;
        }
    }
}

And controller in which I can use many repositories with single database connection:

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 Answer 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.