fd Blog

Daniel Hilgarth on software development

A Fluent Repository: Implementing It for EF

A reader asked how to implement the Fluent Repository for Microsoft’s Entity Framework.
Here is how:

As far as I am aware, Entity Framework doesn’t know a generic method, similar to NHibernate’s Query<TEntity>() (Please correct me if I am wrong).
Instead, it exposes a property per entity on the concrete class derived from DbContext:

public class MyProjectContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }
}

Proceeding from there, a constructor of the base class could take an IQueryable<TEntity> instead of an ISession:

protected EntityFrameworkIQueryableQueryBase(IQueryable<TEntity> query)
{
    if (query == null)
        throw new ArgumentNullException("query");
    _query = query;
}

The concrete query implementation would supply the value of the property:

public class Employees : EntityFrameworkIQueryableQueryBase<Employee, Employees, IQueryEmployees>,
                         IQueryEmployees
{
    public Employees(MyProjectContext context) : base(context.Employees)
    {
    }
    
    // ...
}

I hope this makes it a bit clearer.

Comments