Filtering data based on current user in LightSwitch apps

In many applications, you need to filter data that is only relevant to the particular user that is logged in.  For example, a personal information manager application may only want users to view their own tasks and not the tasks of other users.  Here’s a walkthrough of how you can setup this kind of data filtering in Visual Studio LightSwitch.

I’ll first create a Task table which has two fields: one for the task description and another to store the user name of the user who created the task.

Next, I’ll need to write some code so that whenever a Task is created, it will automatically have it’s CreatedBy field set to the current user.  To do this, I can use Write Code drop-down on the table designer to select the Created method.

Here’s the code:

 partial void Task_Created()
    this.CreatedBy = this.Application.User.Name;

Now we’re at the data filtering step.  What I’d really like to do is have all queries for Tasks be filtered according to the current user.  So even if I model a new query for Tasks then it will automatically get this filtering behavior.  That way I only have to write this code once and it will be applied whenever tasks are queried.  LightSwitch provides a built-in query for each table that returns all instances within that table.  The name of this query is TableName_All.  All other queries for that table are based on that All query.  So if I can modify the behavior of that All query, then every other query that queries the same table will also get that behavior.  LightSwitch just so happens to provide a way to modify the default behavior of the All query.  This can be done through the PreprocessQuery method.  This method is also available through the Write Code drop-down. 

The PreprocessQuery method allows developers to modify the query before it is executed.  In my case, I want to add a restriction to it so that only tasks created by the current user are returned.

 partial void Tasks_All_PreprocessQuery(ref IQueryable<LightSwitchApplication.Task> query)
    query = query.Where(t => t.CreatedBy == this.Application.User.Name);

And that’s all I need to do.  Now, whenever any query is made for tasks it will add this restriction.