Search code examples
mongodbmongodb-.net-driver

MongoDB C# Driver database.GetCollection and magic strings


Just getting into the NoSQL stuff so forgive me if this is a simple question. I am trying to somewhat implement a repository type pattern using a generic repository for the more common operations.

One thing that I have run into that is killing this idea is that in order to get the collection you plan to work with you have to pass a string value for the name of the collection.

var collection = database.GetCollection<Entity>("entities");

This means that I have to hard code my collection names or code up a dictionary somewhere to act as a lookup so that i can map the object type to a collection name.

How is everyone else handling this?


Solution

  • What you can do is "semi-hardcode." You can put the name of the collection in a class name and refere to it:

    public class Entity {
      public static readonly string Name = "entities";
    }
    
    var collection = database.GetCollection<Entity>(Entity.Name);