I’m trying to create a basic unit of work to fully understand the principles. I can re-factor later. I’m simply trying to get it working. I’m having some trouble.
I have a simple entity Code:
public class Code
{
public int Id { get; set; }
public string Type { get; set; }
public string Value { get; set; }
public string Description { get; set; }
}
I have a CodeRepository with one simple Method.
public class CodeRepository
{
public Code GetByCode(string value)
{
// Go to DB and find code. Just using a sample.
var code = new Code();
code.Type = "Dx";
code.Value = "20";
return code;
}
}
I have a simple UnitOfWork class:
public class UnitOfWork
{
private CodeRepository _codeRepository;
public CodeRepository CodeRepository
{
get
{
if (_codeRepository == null)
_codeRepository = new CodeRepository();
return _codeRepository;
}
}
public void Commit()
{
}
public void Rollback()
{
}
}
If I wanted to use the UnitOfWork to call my repository and get a code by name, I’d do:
var uow = new UnitOfWork();
var code = uow.CodeRepository.GetByCode("x");
Where is the connection created to use? I’m uncertain where I need to go next. Also have to use ADO.NET.
Update
Many of the folks below say that the connection should be opened in the repository. If for example, I needed to call 3 different GetBy methods in 3 separate repositories to get values for a view, would I want to open a new connection each time? Or, can I open a single connection?
I would create, open, use and close the connection at the last point where you actually retrieve it from the database, hence in
GetByCode`