0

How can i trap error on creating unique id ?

i used guid instead of auto increment, but i don't know how to trap the error on duplication, i created some code on getting data in SQL using advance linq to know if my id created is exist, but in the end i still have an error.

somebody help me and give me some tip/ link of what is best to use. here my sample code below.

 var nid = Guid.NewGuid();
 var getCartIds = _cartUoW.ShoppingCarts.Get().ToList();
 bool exist = false;
 do
 {
      nid = Guid.NewGuid();
      exist = getShoppingCartId.Any(x => x.Id == nid);
 } while(exist);
tereško
  • 58,060
  • 25
  • 98
  • 150
vaj90
  • 1,803
  • 3
  • 17
  • 17
  • 3
    You haven't generated a duplicate GUID. You have some other bug in your code. – Mitch Wheat Aug 02 '14 at 06:58
  • wait i missed the 1st line – vaj90 Aug 02 '14 at 07:00
  • 1
    You don't need to check the guid for uniqueness it's 99.9999% guaranteed to be unique in your application. http://stackoverflow.com/questions/39771/is-a-guid-unique-100-of-the-time – Viktor Bahtev Aug 02 '14 at 07:07
  • thanks sir, i have now an idea to solve sir, hope this will help, converting guid generated into string and split some character, change split characters into random aplhanumeric and last convert again to guid!... – vaj90 Aug 02 '14 at 07:37
  • 2
    I created 11,998,949 Guids (before running out of memory) in a tight loop calling Guid.NewGuid(); in each iteration. They were all unique (so not a single one was duplicated). Where ever you're problem is, it is not in those few lines... – rene Aug 02 '14 at 09:35

1 Answers1

2

You pretty much can ignore that error. As in: Unless you in code totally crap out, even if you create a million carts per day the chance of getting a double within your lifetime is SLIM. It is so low that the user can as wekk get an "an internal error occured" error until he refreshes.

While each generated GUID is not guaranteed to be unique, the total number of unique keys (2^128 or 3.4×10^38) is so large that the probability of the same number being generated twice is very small. For example, consider the observable universe, which contains about 5×10^22 stars; every star could then have 6.8×10^15 universally unique GUIDs. (from Wikipedia http://en.wikipedia.org/wiki/Globally_Unique_Identifier)

If you regularly get duplicate GUID's then you are not generating them properly / reusing a generated GUID. It is not a fundamental issue with the GUID and I would rather fix this part.

TomTom
  • 61,059
  • 10
  • 88
  • 148
  • sir what should be the best solution for that?, thank again sir – vaj90 Aug 02 '14 at 07:09
  • 1
    @A.J Using your brain and understanding my answer. With all respect, you make up a problem and then ask people for a solution for an imaginary problem. – TomTom Aug 02 '14 at 07:37