Sunday, March 11, 2012

DB Primary Key question

I am using the ASP.Net 2.0 Membership tables and would like to add my own User_Profile table and connect it back to the aspnet_Users table.

Usually I always have the Primary Key be the same as the table name for example my User_Profiles table would have a UserProfileID, my Languages table would have a languageID.

In this case I found this sample

The first - which affords the greatest flexibility, but requires the most upfront effort - is to create a custom data store for this information. If you are using the SqlMembershipProvider, this would mean creating an additional database table that had as a primary key the UserId value from the aspnet_Users table and columns for each of the additional user properties. In the online messageboard example, the table might be called forums_UserProfile and have columns like UserId (a primary key and a foreign key back to aspnet_Users.UserId), HomepageUrl, Signature, and IMAddress.

where it suggests I just use the UserID as the Primary Key in my User_Profiles table. Looking at my database design I could use the UserID in many places as my Primary Key instead of having a Primary Key which relates to the table name and then UserID as just a column in the table.

Are there any pros and cons? Which one is better database design? What is best practice?

Thanks,

Newbie

This approach -- using the same name in the related table as in the

primary -- is appropriate when the related table is a subset of the

objects in the primary table, rather than a linking table between two or more primary entities, and has a

one-to-one relationship to the primary table. Usually the related

table is created to avoid nulls in a core table.

A product

inventory might be an example. It makes sense to have a unique

product_id for each product manufactured by a company. This would of

course be the primary key for the master "products" table. You would

not want to have information specific to a particular line of producs

in this table, though. Say the comapny makes tools, and one of their

lines is sockets. Fields such as socket_type [e.g. hex, star],

drive_size, or socket_size would be irrelevant to many other tools, but

quite necessary to the sockets line. Therefore, you might have a data

structure like:

tools (
product_id char(12) primary key,
tool_class varchar(64),
price decimal,
...
);

sockets (
product_id char(12) primary key references tools(product_id),
socket_type smallint,
drive_size decimal,
socket_size decimal,
...
);

This

works because all sockets are tools, though many tools are not

sockets. Likewise, I would choose product_id here, rather than say

tool_id, for flexibility. The company may also carry other lines of

products for which tool_class would be an inappropriate field. They

are still all products, though.

Hope this helps,

Joseph

No comments:

Post a Comment