Question

I'm developing a .NET web service while trying to maintain a layered architecture that keeps my Models in one project and DB access (DAL) in a different one. The idea behind this is that if I have to change the DB technology, it's just a matter of creating a differnet DAL, while the rest of the application remains unchanged.

In the data-access layer that I'm developing, I am using Mongo DB C# Driver.

I've seen that:

  • Properties named "ID" will be mapped by the C# driver as the database's "_id" (Convention over configuration);

  • Int + Auto-increment in MongoDB is not a good idea;

  • Using Guid's as ID in MongoDB isn't a good idea either;

  • The recommended data type for the ID of documents stored in MongoDB is ObjectID. The C# driver provides a class to represent this;

    • However, if I use this data type (from MongoDB.Bson) in my Models, then they will become dependent on the MongoDB C# Driver and I don't want that: I want my models to be DB-independent; only my DALs can depend on whatever data access technologies I use.

So what data type should I use for my POCOs' IDs in order to have guarantee uniqueness in the DB? Would a string representation of a Guid be horrible in terms of performance?

Your feedback is welcome.

Was it helpful?

Solution

Good question.

From Experience, I can say that you're right: both GUIDs and auto-increment aren't the best idea (with GUID being a lot better than auto-increments), but not only for the reason mentioned in the SO question you linked to, but mostly because you need to be aware of the implications of monotonic vs. non-monotonic keys.

With the ObjectIds, I see three options:

  • Map between domain model and DAL. In the domain model, you could use the objectid's string representation. That's a bit annoying, but it forces you to separation of concerns.

  • Use your own data type and implement a type converter / mongodb serializer. I haven't tried that but I don't see why this wouldn't work.

  • Accept the MongoDB dependency. After all, if you really swap out your database, that will be a huge task. Different databases have very different characteristics and require very different data models. The whole "swap out the database" in a minute is bogus IMHO, it's never that easy and a database is a much leakier abstraction than anyone wants to admit. Trying to keep independent is a PITA. Anyway, doing a seek-and-destroy on the word ObjectId will be less than 1% of the other work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top