C# - Generate “identity” like Id's with NoSQL (MongoDB)?

时光总嘲笑我的痴心妄想 提交于 2019-12-12 17:00:19

问题


I've been using MongoDB with C#, and have been using ObjectIds, then later GUIDs for my Entity Ids. I hate looking at these Id's, I think it's counter intuitive... I'd really like to be able to use integers or longs, like relational DBs Identity column. But I'm having a hard time finding a way to do it. If I use collection max + 1, that will lead to race conditions. I've read about using a Hi-Lo Generator algorithm, but how does that work? What if I have 10 app servers running the same code? Does that mean I have to have 10 hi lo identity ranges per collection?

If someone can point me to a C# algorithm to share that would be great! I've seen RNGCryptoServiceProvider by the way, but that's not guaranteed to be unique, and it's not a sequential int/long Identity. I'd rather use Hi-Lo at that point...

Thanks, Tim


回答1:


You can write your own id generator and use it. Here you can find how. But ObjectId was designed to be unique across all shards/replica sets. So each shard can generate unique id independently from others. With int id in distributed database you will have many problems.




回答2:


Guids may not be pretty to look at, but they are tested and tried.

You can go out of your way to try and prevent clashes on integer sequences but in the end, I think you'll find it's not worth the trouble. This is especially true for distributed environments that tend to change over time.




回答3:



This is way to go: github.com/alexjamesbrown/MongDBIntIdGenerator



来源:https://stackoverflow.com/questions/6855084/c-sharp-generate-identity-like-ids-with-nosql-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!