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