Search code examples
c#entity-framework-6entity-framework-plus

zzzprojects/Entity Framework Plus global filters with dynamic variables


I need to create a global filter for my db context. The filter should show only objects with the same companyId as the current user.

Right now, I am passing companyId like so:

  public MyDB(int companyId) : base("name=DefaultConnection")
    {

            this.Filter<BaseModel>(q => q.Where(x =>  (x.CompanyId == companyId || x.IsGlobal==true) && x.IsDeleted == false));
    }

But, It doesn't work well with lazy loading(virtual properties). So, I need to implement a global filter and I have no idea where to start and how to pass the companyId variable into it.

Here is my ApplicationUser

 public class ApplicationUser : IdentityUser
{
    public int CompanyId { get; set; }

}

CompanyId is equal to current's user CompanyId. Each user could belong to one company. So, companyId won't change while a user logged in.

Thank you for all your help


Solution

  • Disclaimer: I'm the owner of the project Entity Framework Plus

    So, companyId won't change while a user logged in.

    You cannot use a Global Filter for a predicate that's not global to all queries.

    If you use a global filter, all queries will be compiled using by example the company A. However, if someone from the company B log into your application, all filtered query will still use compiled query from the company A.

    Unfortunately, for your scenario, our EF+ Query Filter cannot be used.

    I recommend you to try instead EntityFramework.DynamicFilters, they maybe handle better this kind of scenario and our library.