Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between creating Guid keys in C# vs. the DB

Tags:

c#

sql

guid

We use Guids as primary keys for entities in the database. Traditionally, we've followed a pattern of letting the database set the ID for an entity during the INSERT, I think mostly because this is typically how you'd handle things using an auto-increment field or whatever.

I'm finding more and more that it's a lot handier to do key assignment in code during object construction, for two main reasons:

  1. you know that once an object's constructor has run, all of it's fields have been initialized. You never have "half-baked" objects kicking around.
  2. if you need to do a batch of operations, some of which depend on knowing an object's key, you can do them all at once without round-tripping to the database.

Are there any compelling reasons not to do things this way? That is, when using Guids as keys, is there a good reason to leave key assignment up to the database?

Edit: A lot of people have strong opinions on whether or not Guids should be used for PKs (which I knew), but that wasn't really the point of my question.

Aside from the clustering issue (which doesn't seem to be a problem if you set your indexes up properly), I haven't seen a compelling reason to avoid creating keys in the application layer.

like image 911
AwesomeTown Avatar asked Jan 30 '09 18:01

AwesomeTown


1 Answers

I think you are doing just fine by creating them on the client side. As you mentioned, if you let the db do it, you have to find some way (can't think of any really) to get that key. If you were using an identity, there are calls you can use to get the latest one created for a table, but I'm not sure if such exists for a guid.

like image 134
Otávio Décio Avatar answered Oct 04 '22 11:10

Otávio Décio