I’m building an ASP.NET MVC3 website with an code first database and have the following question:
Is it possible to make an instance of MyDbContext class with an additional argument set which will be used for filtering the results of calls to mydbcontext.
I want to use this for restricting the resultset to the current user that is logged in on my asp.net mvc website.
Any directions would be great!
I don’t see why that should be a problem. Something like this should work:
Update
To make it impossible for your
MyDbContextto be abused, you could put all your database code and models into a separate project/assembly. Then make yourDbContextaninternalclass (instead ofpublic), then create apublicclass (FilteredDbContext) that wraps yourMyDbContextand exposes methods that allow you to only grab the data your allowed to see. Then in your main assembly (your web project), you will only be able to useFilteredDbContext.So, for example:
If
NorthwindandFilteredNorthwindare in a separate assembly from your web app, you can instantiate onlyFilteredNorthwindfrom your web app.Update 2
If you use a ViewModel, then your web app can’t get back to the list of all products for a category because you extract out only the properties you need (and only the properties the user is allowed to see).