Question

Lets assume that below code retrieves data from database via Unit Of Work pattern. Since the GetByID is the common operation, it can be declared inside Repository class.

UnitOfWork w = new UnitOfWork();
w.someRepository.GetByID(10);

What if i need to call GetByID method in 10 seperate files. Should i create an instance of UnitOfWork class and call GetByID in every time or does the code-block below is valid for UnitOfWork pattern?

public class SomeRepositoryProvider {

public tbl_somerepoclass GetByID(int id) {

   UnitOfWork w = new UnitOfWork();
   return w.someRepository.GetByID(10);


}
}
Was it helpful?

Solution

Generally you shouldn't even need UnitOfWork when you want only to retrieve data from database. UnitOfWork is more like transaction to db - you try to persist some set of data to db in one go - if everyfing goes ok it is saved, if not then everything is rollback. To get entities by ids you should only need Repositories. The best solution I encountered in my practice is to for each entity prepare Repository class and prepre there useful methods. Only if you want to save the data use UnitOfWork. So generally you should use your repostiory like that:

someRepository.GetById(10);

When you instantiate Repository just pass to its constructor proper object needed for the operations - in case of entity framework ver. > 4.0 DbContext.

If you want to add new entity use it like that:

someRepository.Add(newEntity);
unitOfWork.Save();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top