I am reading up upon the Repository usage. Sometimes I see that a repository is a property of an entity. I was wondering what the pro’s and cons are.
public interface IRepository<T>
{
T GetById(int id);
void Update(T);
}
public class FooRepository : IRepository<Foo>
{
public Foo GetById(int i)
{ /* code ..*/ }
void Update(Foo)
{ /*code..*/ }
}
public class Foo
{
public IRepository Repository {get;set;}
public void Update()
{
Repository.Update(this);
}
}
Why use this apporach? Doesn’t it makes more sense to use the repository and the entity object seperated? So that the entity object doesn’t know about any repositories?
EDIT:
But what if you have one main object and different sub-objects:
public class MainObject
{
public int Id {get;set;}
public List<ISubject> SubObjects {get;}
}
public interface ISubObject
{
}
public class SubObjectA : ISubObject
{
public string SomeProperty {get;set;}
public int Id {get;set;}
public int MainObjectId {get;set;}
}
public class SubObjectB : ISubObject
{
public string AnotherProperty{get;set;}
public int Id {get;set;}
public int MainObjectId {get;set;}
}
So SubObjectA and SubObjectB are different types but implement the ISubject interface. The main object has a list of these subobjects. Each sub-object has it’s own repository. How would you load the sub-objects?
Some entity implementations require access to the context in which they are created, to implement lazy loading for example. Consider the following:
You can return sub-classes of MyEntity from the an MyEntity implementation, that require a reference to the repository that created it.
I would say, that keeping a reference to the source repository in a class derived from an entity is fine, on the other hand, the base entity class should not have knowledge about the repository.