Global filters in Entity Framework

Asked

Viewed 50 times

1

I would like all of mine DbSet filter all calls

I mean, I’d like all the DbSet make the following filter:

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

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

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

  • could give an example?

  • @Tobymosque Editei

  • I am unable to formulate an answer now, but you can check out the following article: http://www.agile-code.com/blog/entity-framework-code-first-applying-global-filters/

  • @Tobymosque I got to look at this link...but I thought there would be easier way, besides overwriting everything

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();
    }
}

Use:

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

Another alternative is to define a property in its uncharted context and make the access only by 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);
        }
    }
}

Packets

There is also the Nuget package option:

  • So if I have 1000 models, I have to do 1000 methods ? LOL

  • @Rod See the @Tobymosque link. It has a very cool generic implementation there. It can improve the extension method, by the way, but would use Expressions and it’s really hard to write.

  • a pity the EF doesn’t have it native =( , I saw a lib in nuget called Entityframework.Filters

  • I used Entityframework.Filters, actually I used the 2 you mentioned, I preferred Filters because it seemed more "mature" and the guy who keeps more active in the community

Browser other questions tagged

You are not signed in. Login or sign up in order to post.