Bobson
Bobson

Reputation: 13706

MVC RouteUrl performance with database lookups in constraints

Our MVC3 routing engine has a couple entries which have a constraint which involves a database lookup to evaluate. For example:

        routes.MapRoute(
            "Product",
            "{manufacturer}/{partNumber}",
            new { controller = "Product", action = "Details", manufacturer = "" },
            new { manufacturer = new ManufacturerConstraint() }
        );
        routes.MapRoute(
            "Store",
            "{store}/{action}",
            new { controller = "Store", action = "Index" },
            new { store = new StoreConstraint() }
        );

where ManufacturererConstraint() involves a database lookup and StoreConstraint() does not.

We're using RouteUrl to generate a link similar to:

RouteUrl("Product", new { manufacturer = product.Brand, partNumber = product.PartNumber });

Three questions from this:

  1. Does our usage cause a database lookup?
  2. If I generated a route for the "Store" route, would that also generate a lookup as it tests it against all routes? Or would it only do the one test for the specified route?
  3. If it does hit the database in this usage, is there a way to use RouteUrl that wouldn't?

Upvotes: 0

Views: 283

Answers (1)

Max Toro
Max Toro

Reputation: 28618

Does our usage cause a database lookup?

Yes, if the constraint is setup to work on UrlGeneration. Url.RouteUrl runs all constraints, just like Url.Action. The only difference is that you are explicitly saying which route you would like to use, instead of testing each route until one matches.

If I generated a route for the "Store" route, would that also generate a lookup as it tests it against all routes? Or would it only do the one test for the specified route?

I think I answered this above.

If it does hit the database in this usage, is there a way to use RouteUrl that wouldn't?

Setup the constraint so it doesn't run on UrlGeneration (using the routeDirection parameter). Personally, I'd cache the lookup data instead.

Upvotes: 1

Related Questions