views:

50

answers:

2

I have an ASP.NET MVC application that uses Linq to SQL repositories for all interactions with the database.

To deal with data security, I do trimming to filter data to only those items to which the user has access. This occurs in several places:

  1. Data in list views
  2. Links in a menu bar
  3. A treeview on the left hand side containing links to content
  4. Role-based security
  5. A special security attribute, inheriting from AuthorizeAttribute, that implements content-based authorization on every controller method.

Each of these places instantiates a repository, which opens a Linq to Sql DataContext and accesses the database. So, by my count, each request for a page access opens at least six separate Linq to SQL DataContexts.

Should I be concerned about this from a performance perspective, and if so, what can be done to mitigate it?

+1  A: 

Good question, I don't believe you're going to have anymore issues here than with normal query operation. The translation from Linq Expressions to sql queries is a relatively involved process, but will probably pale in comparison to the actual execution of the query and network latency.

LorenVS
I should add to this that although it doesn't seem natural, the LinqToSql DataContext itself is actually quite light-weight. The actual creation of the DataContext shouldn't have any effect on your site, the actual delay is simply going to be running the 6 queries.
LorenVS
+1  A: 

In almost all of my MVC applications I use a BaseController. Typically I will use a factory to create an instance of the DataContext in the BaseController constructor (unit tests pass in a mock factory instance, the null constructor results in a default instance of the factory being created). While not strictly necessary, I do Dispose the created DataContext in OnResultExecuted in the BaseController. Both the "default" data context and the factory are exposed as protected properties on the BaseController class so they can be used by all inheriting controllers.

If I need some operations to take place outside the "default" DataContext, I simply use the context factory to create a new, separate instance as necessary.

I confess that I do this mostly for convenience and code legibility. I think the data contexts themselves are lightweight enough that I don't gain much performance. I no longer, however, have to write the using (var context = ... code in every action method.

tvanfosson