Question:
I'm about to start a new project in MVC 4 with Entity Framework, researching I found several examples here on SOpt of models that use GUID as ID and some questions came to me:
What is the advantage of using GUID as a primary key?
Is it feasible to use it on a small project?
Are there any cons to using GUID?
Answer:
What is the advantage of using GUID as a primary key?
Benefits:
- Eliminates classic primary key
IDENTITY
problems, as the record limit increases considerably (roughly 5,316,911,983,139,663,491,615.228,241,121,400,000 records), and avoids gaps between Id's; - It makes a human search for data (especially malicious ones) unpredictable, improving security. The search is now done by another column, and not by Id, which may not be safe in a modern application;
- In the examples given in other answers, a user can try to easily access a record by putting any Id's in the address bar and making
GET
requests testing the existence of a record or not;
- In the examples given in other answers, a user can try to easily access a record by putting any Id's in the address bar and making
- Takes the responsibility for column generation from the database. The column is generated by the application;
- It eliminates almost all concurrency issues related to inserting and updating records. The others can be resolved with explicit transactions;
- Data migrations and joins are tremendously simpler as there is no problem of reserving value ranges for the primary key;
- More natural for Ajax with aggregated and dependent entities because there is no need to work with temporary keys. The key generated when creating the record can be used in recording the record, or it can be treated as temporary and replaced when persisting the main entity and its derivatives.
Is it feasible to use it on a small project?
IT'S. There is no problem using it.
Are there any cons to using GUID?
Yes, as with any other choice of your application's primary key data pattern:
-
Guid
s typically use 16 bytes . This number can vary depending on the implementation, whereasint
uses 4 bytes andbigint
uses 8. Depending on the data volume, usingGuid
s can significantly increase the volume of data stored;- A caveat here is necessary: the difference is not as glaring as you might think, especially considering the data volumes supported by current hosting services.
- The performance overhead is on the order of 10%;
- Depending on the size of the table, using completely random
Guid
s can cause performance loss if the index isclustered
. This is because there is no logical ordering pattern for the index to follow. One of the alternatives for this is to put some pattern of sequence in theGuid
generation, as explained in this Code Project article .