I am reletively new to Entity Framework and LINQ. I have the following code with returns a list of suppliers
public class SupplierRepository
{
private DataContext db = new DataContext();
public IQueryable<Supplier> FindAllSupplier()
{
return db.Suppliers;
}
}
This works fine, but I know you can use Generics with Linq and EF. so that the above code would look something like this…
public class GenericRepository
{
private DataContext db = new DataContext();
public IQueryable<T> FindAll<T>()
{
return ...
}
}
So that I can use it to return any type in my EF model, but I am not sure how to implement this. Can anyone advise please?
Instead of returning an
IQueryable<T>let your repository implementIQueryable<T>and instead of wrapping aDataContextinside the repository, wrap both theDataContextand the repositories inside a unit of work. Your repository can than look like this:I use this approach to effectively hide my O/RM behind an abstraction, which allows me to unit test my applicationm while still allowing to use LINQ over my repositories and have the unit of work pattern.
You can read all about it here: Faking your LINQ provider.