How to Filter result in MVC 4 based on user

前端 未结 7 793
面向向阳花
面向向阳花 2020-12-13 22:26

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

相关标签:
7条回答
  • 2020-12-13 22:58

    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 :)

    0 讨论(0)
提交回复
热议问题