Question

I would like to grab results from a database, using Entity Framework, and filter those results based on whether an asp.net user is an admin, using a static method.

Given this code, could there be instances where a non-admin user will be served admin results?

If so how would I achieve my desired result using a static method?

public class Listings
{
    public static List<Listing> GetListings()
    {
        bool isAdmin = User.IsInRole("admin");

        List<Listing> listings;

        using(DBContext dbContext = new DBContext())
        {
            listings = (from l in dbContext.Listings
                        where l.Public || isAdmin
                        select l).ToList();
        }

        return listings
    }
}
Was it helpful?

Solution

This depends on where you get the DbContext from. Its instance methods are not thread safe.

If it is created in a ASP.NET request scope (you have a new instance in each of independent requests) then you are safe, the code is correct.

If it is shared then anything can happen, most probably you would get exceptions from concurrent access to the same db context.

Learn more from similar threads

One DbContext per web request... why?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top