Graham.Fraser
Graham.Fraser

Reputation: 389

ASP.NET MVC Model id type --- best practices

Simple question. I have several different models stored in SQL databases. A Table of images records with byte data, large multi-field user data table, ect. All of these models require primary keys. Most beginner tutorials show usage of int for ids. Is this standard and professional. I find it odd to start use int since is variable in length and starts with 1 :S

Sorry for the amateur question, but I couldn't find any adequate materials on the subject via google.

Upvotes: 1

Views: 1682

Answers (4)

Jesse Hallam
Jesse Hallam

Reputation: 6964

There's nothing implicitly unprofessional about the use of INT or any other integral data type as a primary key or identity column. It just depends on your business needs. In the interest of keeping programming as simple as possible, the INT data type is a fine choice for many business needs:

  • It is capable of representing about 2.1 billion unique records.
  • It consumes minimal hard disk space in modern hardware.
  • It is fast for SELECTs and UPDATEs.
  • It is fairly ease to refactor up to a larger integral if the number of records threatens to exceed the limits. BIGINT can address more records than you can put in your database. Seriously.

One reason you might not want to use an integral primary key:

  • You might use a Guid (or UNIQUEIDENTIFIER in SQL Server terms) for global uniqueness. In other words, if you migrate your data to another location, the primary key should still be unique.

Upvotes: 1

Pein
Pein

Reputation: 1246

Guid type is also used sometimes as an ID. It has some benefits, like fixed length, global uniqueness and unpredictability. And some issues like lower search performance and it's hard to remember.

Upvotes: 0

MartinHN
MartinHN

Reputation: 19772

This is 100% ok, and widely used. Some use longs for primary keys, since their max value is bigger. Though, not necessary in most occasions.

Upvotes: 0

devuxer
devuxer

Reputation: 42374

Yes, int is industry standard.

Even beyond databases, I rarely see C# code with uint or any of the other variants for representing whole numbers. Occasionally byte is used in arrays. long is used when int may not be big enough to cover all possibilities.

One advantage of always using int is that you can pass id variables around without having to worry about casting between the different integer types.

Upvotes: 0

Related Questions