I have seen this code in a few places. What is IEntity doing in the code below? I know that IEntity is not an interface, even though it's prefixed with "I". Additionally, I understand it may be acting as an ID for the entities returned from the repository. When would this ID be set? I'm looking for a good explination of the interface use of IEntity and how it relates to "T".
Code from: http://blog.falafel.com/implement-step-step-generic-repository-pattern-c/
public class IEntity
{
public string Id;
}
public interface IRepository<T> where T: IEntity
{
IEnumerable<T> List { get; }
void Add(T entity);
void Delete(T entity);
void Update(T entity);
T FindById(int Id);
}
It's a generic type parameter constraint to define what type of entities can handle a repository.
That is, TEntity is IEntity or any derived class, but at least TEntity references will gain compile-time access to IEntity members. This is a huge improvement since you don't need to perform run-time type checks prior to casting a reference because you don't need a cast anymore.
For example, Add(TEntity) without generics would look as Add(Entity) which would force the runtime to perform an upcast (f.e. Add(new DerivedEntity()) which upcasts DerivedEntity to Entity).
When using generics, an IRepository<DerivedEntity> will compile Add as Add(DerivedEntity), so, where's the cast right now when adding an entity of type DerivedEntity? ;)
When would this ID be set?
Usually the repository implementation should set the TEntity.Id:
public void Add(TEntity entity)
{
// "entity" reference can access TEntity.Id because TEntity is
// at least IEntity
entity.Id = Guid.NewGuid().ToString();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With