Global Filters in Entity Framework

1

I would like all my DbSet to filter all calls

That is, I would like all DbSet to do the following filter:

Where(x => x.active == true)

Without the need of all the time I have to do dbo.Models.Where(x => x

How could I create something like this without using respository pattern ?

    
asked by anonymous 26.02.2015 / 20:16

1 answer

1

You can create an extension method, for example:

public static class EntityFrameworkExtensions 
{
    public static IEnumerable<T> Ativos<T>(this IDbSet<T> dados) 
    {
        return dados.Where(x => x.active == true).ToList();
    }
}

Usage:

meuDbSet.Ativos().Where( ... ).ToList();

Another alternative is to define a property in its non-mapped context and only access it:

public partial class MeuContexto: DbContext
{
    public MeuContexto()
        : base("name=ConnectionString")
    {
    }

    public DbSet<Modelo> ModelosSet { get; set; }

    public IQueryable<Modelo> Modelos
    {
        get
        {
            return ModelosSet.Where(a => a.active);
        }
    }
}

Packages

There is also the option of NuGet packages:

26.02.2015 / 21:54