How to limit data only to logged in user in Entity Framework Core Identity Easily

.net-core c# entity-framework entity-framework-core


I am using Entity Framework Core Identity. All my Entities have a property called CreatedBy, a Foreign Key to the built in Identity User table. I have a GetAll() endpoint in my API that returns all records from the tables associated with these entities. I want this GetAll() to only return records that were created by the currently logged in user. I can get the UserId from the HttpContext, but I was wondering if I could automatically limit the records.

For example, I can perform an action like this to get this behavior:

return _context.Entities.Where(e => e.UserId == userIdFromHttpContext).ToList()

However this is some extra condition I would have to put in every single Where clause in every single future Get method I'd write. This is highly redundant to me.

I would like to simply just call

return _context.Entities.ToList()

which would automatically filter all the records out not associated to the currently logged in user.

Is there anything I can do, to configure some sort of "automatic" pre-defined where clause in the DbContext that applies to all tables in the context, just once? Preferably I'd like to inject the HttpContext into the DbContext (I know this can be done) and configure this behavior in the OnConfiguring() method there.

edit: I'd like to avoid a wrapper around the class around the context if possible as well. This application is being worked on by college students and I'd like them to use the "vanilla" Entity Framework conventions for grabbing data as opposed to working with some sort of custom implementation

2/8/2019 9:03:39 PM

Popular Answer

you could use a Global Query Filter (more info here) In a nutshell, you can specify a Where during the call to OnModelCreating, and it will be applied every time you try to access that entity collection.

2/8/2019 9:17:31 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow