MVC – Does MVC Expose Database Primary Keys?

asp.net-mvcmvc

I'm going through a MVC tutorial, and I notice that convention seems to be to expose a tables primary key on detail pages/urls (ie. /Movies/Details/5 as an example from the tutorial).

It's obviously not a problem for things like a movie record or a SO post, but it might be a bit different for an invoice or transaction with confidential information on it if the key was sequential or guessable.

So, is it just this tutorial or do MVC apps typically expose a tables primary key? Is there a common library or pattern for hiding the key if you don't want to expose it?

Best Answer

And that's why I think those tutorials simplify things to a degree that confuses the newcomer.

Try to do a little "tabula rasa" and think the process from scratch, and decoupling the concepts.

First of all, MVC is a presentation layer. It does not (or should not) even know what is backing it up. It could be a database, an xml file, a text file, an in-memory collection, whatever. It should be abstracted away.

What does MVC understand? Receives an HTTP request, parses it using the route engine, resolves to the corresponding controller/action method and does whatever you write in the action method. End of the story.

Do you ask for an id which, behind the scenes, corresponds to a database surrogate key? MVC doesn't know that. For it, it's just an int parameter of a method.

It's entirely up to you how you decouple your logic and layers, how you retrieve data and check for security.

Assume you get asked for Products/Detail/1. Is your action method under authentication (using the authorize attribute)? If so, are your products only visible to certain users?

You'll pass to a business logic method the requested id along with the username, and that method will tell you "here's your product" or "sorry, you cannot view this" based on the logic inside. And heck, if you designed it well even the business logic method won't know if behind the scenes it used a database or anything else to retrieve the product.

I hope this little explanation clarifies things a little. MVC is just about handling HTTP requests and returning a view or some json data or whatever you want to return to the users. Anything that backs it should be abstracted away and implemented as you see fit.