I’m working with MongoDB for the first time in a .NET application. I’m struggling with the model
and “default” way of working which makes my application maintainable by multiple people.
One struggle I’m encountering is how to work with the ObjectId key in code. Currently, I define “MongoEntities” which have an Id of type ObjectId. This seems to be optimal for querying. However,
in the controller layer, this means that I have to map a string from the route to an ObjectId using the TryParse method in every action. A solution would be to add a Custom Model Binder on a type that inherits from ‘ObjectId’ but I’m not sure whether this is the best possible solution.
There are a few ways you can handle the ObjectId key in your .NET application when working with MongoDB:
Use a custom model binder: You mentioned this option and it is a good way to map a string from the route to an ObjectId. This allows you to encapsulate the logic of converting the string to an ObjectId in a reusable way. You can also add additional validation to ensure that the string is a valid ObjectId before converting it.
Use a custom ObjectId class: You can create a custom class that inherits from ObjectId and add methods for parsing and validating the string representation of an ObjectId. This can be useful if you want to add additional functionality to the ObjectId class. You can then use this custom class in your controller layer instead of working with the ObjectId directly.
Use a helper method: You can create a helper method that takes a string as an argument and returns an ObjectId. This helper method can contain the logic of converting the string to an ObjectId and validating it. You can call this helper method in your controller layer whenever you need to convert a string to an ObjectId.
Ultimately, the solution you choose will depend on the specific requirements and constraints of your application. The custom model binder and custom ObjectId class options are good choices if you want to encapsulate the logic of converting a string to an ObjectId in a reusable way. The helper method option is a simple solution that works well if you have a small number of conversions to make.