I’m about to show my inexperience here, but hey – like any developer I want to learn.
Given the following interface:
public interface IRepository
{
entityDB Database { get; set; }
IQueryable<T> All<T>() where T:class, new();
T Single<T>(Expression<Func<T, bool>> expression) where T : class, new();
IList<T> Find<T>(Expression<Func<T, bool>> expression) where T : class, new();
}
How would I go about creating a usable repository class such that I can have the generic type T replaced with a strong type?
Assuming I have a photo portfolio site that has a Photos entity and a CameraSettings entity, how do I define the types – and therefore the L2S – that gets included in my concrete class? Currently when I implement the class, it expects the following form:
public class PhotoRepository : IRepository
{
public override IQueryable<T> All<T>()
{
// code goes here...
}
public override T Single<T>(System.Linq.Expressions.Expression<Func<T, bool>> expression)
{
// ...and here...
}
public override IList<T> Find<T>(System.Linq.Expressions.Expression<Func<T, bool>> expression)
{
// ... and let's not forget here.
}
}
Am I even going about this the right way, or should I be using an interface that looks like this:
public interface IRepository<T> where T:class
{
entityDB Database { get; set; }
IQueryable<T> All();
T Single<T>;
IList<T> Find();
}
I just want to get my unit tests working correctly and be confident that I’m not learning bad (or just plain ugly) habits. Appreciate the steer in the right direction.
If I’ve understand you right you want create separate repositories for every your entity (or just for a few of them). In this case appropriate solution is to use the second version of the interface that you posted. Like this:
And implementation of
PhotoRepositorywill look like this:Also if your repositories will operate with the Entity Framework entities you can define the IRepository interface more exactly: