Add Triggers to EF

I work on users and permissions. Module for some projects using C # 4.0 and Entities Framework.

and in the proposed scenario, I have to give users permissions for such data as:

  • grant the user "John" permission for employees in a specific department.

therefore, I decided to process this permission in the Entity Framework and add some conditions for all selected queries before executing it. In other words, I need to add something like trigger to the entity to modify the select query before executing it.

Is there a way to do this within an entity?

+4
source share
1 answer

You can add multiple conditions to IQueryable dynamically. So you can do something like:

 [PrincipalPermission(SecurityAction.Demand, Role="DepartmentManager")] public IEnumerable<Employee> GetManagedEmployees() { // build base query var query = from e in context.Employees select e; // add condition query = AddDepartmentPermissions(query); return query.AsEnumerable(); } 

And your AddDepartmentPermissions will look like this:

 private IQueryable<Employee> AddDepartmentPermission(IQueryable<Employee> query) { int departmentId = GetAllowedDepartmentSomewhere(); return query.Where(e => e.Department.Id == departmentId); } 

This is an example where PrincipalPermission does not allow GetManagedEmployees to be called for non-manager roles, and AddDepartmentPermission adds part of the request to select employees only from the allowed department.

The main thing is that you can wrap IQueryable<T> in methods that will modify the query. I believe that even the ability to add interception (aspects) can even be directly to the properties that display the ObjectSet , and dynamically add request elements related to security.

+1
source

Source: https://habr.com/ru/post/1341523/


All Articles