I have a custom authenticantion, when user logs in, I keep the necessary information on Session/Cache...
So, I have some Views with DropDowns that must show data fil
This is a pretty default scenario that you want a user to see only data relevant to him.
Personally, I never did DB-Calls within the controller, I always had an additional DataLayer which I wired with an IoC-Container.
This DataLayer should only know the DataBase and how the data is stored, and filter this data correctly. You can argue if the DataLayer can use the HttpContext to automatically retrieve the user-ID or should get it as an argument.
So you not to have write always that expression you could also create a function, which will give you the correct Where-Lambda-Expression and you can simply use it:
public Expression<TModel> GetUserFilter<TModel>()
{
var userId = GetUserId();
var itemParameter = Expression.Parameter(typeof(TModel), "item");
var whereExpression = Expression.Lambda<Func<TModel, bool>>
(
Expression.Equal(
Expression.Property(
itemParameter,
"Id"
),
Expression.Constant(userId)
),
new[] { itemParameter }
);
return whereExpression;
}
And now you can call this function in you Controller or DataLayer:
Model.MyList = repository.GetAll().Where(GetUserFilter<Repository>());
You can of course change the names and make it shorter so that it's actually less to write :)