Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make Global Query Filters in Entity Framework 6? by OnModelCreating?

Tags:

I try to make a global query. I know that this is possible in EF Core 2.0 however I need to do it using EF 6.

I try to do something like this in EF 6: (IsDeleted is a property in my Class Cliente as boolean)

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Client>().HasQueryFilter(x => x.IsDeleted= false);
}

I will appreciate your help, thank you!

like image 233
Antonio David Restrepo Carvaja Avatar asked Dec 15 '18 14:12

Antonio David Restrepo Carvaja


1 Answers

What I believe is that you want to implement soft-delete in your application. To apply a global query filter you can follow this approach too.

first of all, install System.linq.Dynamic Library using NuGet.

Then create one extension Method like:

public static IQueryable<T> WhereDeleted<T>(this IQueryable<T> source)
{
    return source.Where("IsDeleted== false"); 
}

and then you can call other methods like this:

var client = db.Client.Include("whatever you need")
                      .WhereDeleted().Where(c => c.Age < 30);
like image 161
BthGh Avatar answered Oct 13 '22 07:10

BthGh