Here is the simple snippet:
public interface IRepository<T>
{
T Get(int id);
}
public class Repository<T> : IRepository<T> where T : class
{
private readonly IRepositoryContext _repositoryContext;
private IObjectSet<T> _objectSet;
public Repository(IRepositoryContext repositoryContext)
{
_repositoryContext = repositoryContext;
_objectSet = repositoryContext.GetObjectSet<T>();
}
public virtual T Get(int id)
{
return ObjectSet.First(x=> x.Id == id)
// that wouldn't work because there is no guarantee that T entity has Id property
}
Now, as you can see I can instantiate Repository for any entity object and use methods defined (although in the example we have only Get(). But I can’t use any constrains in expressions, unless I create non-abstract classes for each entity of T based on IRepository<T> and then implement methods the way I want.
But what if I need to use a method like Get which implementation stays the same for probably all entities (every entity has an Id).
How to do that?
I thought, I could create an abstract entity in EF data model designer, mapped to nothing, and mark that as the base type for all other entities, but It’s asking for a mapping i.e. table. I tried to go with a complex type instead – that wouldn’t let me inherit from it.
So, show me please the most efficient way to achieve that
That’s not really the repository’s role to know whether there’s an ID or not in your object.
Most repositories implement the
Singlemethod like this