0

I have a Person class with a collection of Appointments. I'd like to make a FutureAppointments collection that contains only Appointments that happen in the future so I can simply Include that filtered collection.

You can do this in NHibernate like so: NHibernate filter collection

How can I do the same in Entity Framework?

Community
  • 1
  • 1
Mike Cole
  • 14,474
  • 28
  • 114
  • 194

1 Answers1

0

There isn't a way to accomplish this with Entity Framework out of the box. You would have to create your own implementation. The goal is to apply the filters to the applicable data sets when creating the context. Here is one approach:

Filter interface:

public interface IFilter<T> where T : DbContext
{
    T DbContext { get; set; }
    void Apply();
}

Context implementation:

public class MyContext: DbContext
{
    public void ApplyFilters(IList<IFilter<MyContext>> filters)
    {
        foreach (var filter in filters)
        {
            filter.DbContext = this;
            filter.Apply();
        }
    }

    public IDbSet<MyDbSet> MyDbSet { get; set; }
}

Filter Implementation:

public class ActiveSetFilter:  IFilter<MyContext> 
{
    public MyContext DbContext  {  get;  set;  }

    public void Apply()
    {
        DbContext.MySet= new FilteredDbSet<MySet>(DbContext, d => d.IsActive);
    }
}

Using the filter:

var context = new MyContext();
context.ApplyFilters(new List<IFilter<MyContext>>()
                     {
                         new ActiveSetFilter()                                         
                     });

var myDbSet= context.MyDbSet.ToList(); // will only have active rows

Here is a sample of what the FilteredDbSet could look like. It's essentially a context constructor that takes an expression as a parameter.

* EDIT *

Filter on includes:

DbContext.MySet = new FilteredDbSet<MySet>(DbContext, d => d.IsActive && d.All(x => x.IsActive));
SOfanatic
  • 5,523
  • 5
  • 36
  • 57
  • Does this filter data on child collections when using Includes? – Mike Cole Jun 17 '13 at 20:35
  • @MikeCole meaning if you filtered out child collections in the filter itself, but then include them, will they come up? See my edit to see if maybe that's what you mean. – SOfanatic Jun 17 '13 at 21:48