BowlingForGreens
BowlingForGreens

Reputation: 23

Entity Framework Query Filter

Is it possible to add a sort-of a global filter to an Entity Framework object context? Such as having an ObjectMaterialized which can return an indicator of whether or not to include a given object in the result set.

Upvotes: 1

Views: 1709

Answers (2)

Jim Wooley
Jim Wooley

Reputation: 10418

Are you trying to do something like only show the active Customers? If so, you can use Inheritance and create an ActiveCustomer type and add a condition in your mapping to Status == "Active". Then set your Customer type as an Abstract Base Class to prevent direct instantiation. You can then query your model for Customers.OfType<ActiveCustomer>().

Upvotes: 1

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364409

No it is not possible. Entity framework and its built in providers don't have any support for global filters.

You can achieve some basic filtering with simple wrapper:

public class MyContext : ObjectContext
{
    private ObjectSet<MyEntity> myEntities;

    public Expression<Func<MyEntity, bool>> GlobalMyEntityFilter { get; set; }

    public IQueryable<MyEntity> MyEntities
    {
        get
        {
            if (GlobalMyEntityFilter != null)
            {
                return myEntities.Where(GlobalMyEntityFilter);
            }

            return myEntities;
        }
    }  
}

Upvotes: 2

Related Questions