Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 543
JBeckton Avatar asked Dec 07 '22 13:12

JBeckton


1 Answers

I wrote a class to manage DB transactions

First you need a base class for all entities:

public abstract class Entity
{
    public ObjectId Id { set; get; }
}

then an static class to manage all:

public static class MongoDB
{
    private static string connectionString = "mongodb://localhost";
    public static string DatabaseName { get { return "test"; } }

    private static MongoServer _server;
    private static MongoDatabase _database;

    public static MongoServer Server
    {
        get
        {
            if (_server == null)
            {
                var client = new MongoClient(connectionString);
                _server = client.GetServer();
            }

            return _server;
        }
    }

    public static MongoDatabase DB
    {
        get
        {
            if(_database == null)
                _database = Server.GetDatabase(MongoDB.DatabaseName);

            return _database;
        }
    }

    public static MongoCollection<T> GetCollection<T>() where T : Entity
    {
        return DB.GetCollection<T>(typeof(T).FullName);
    }

    public static List<T> GetEntityList<T>() where T : Entity
    {
        var collection = MongoDB.DB.GetCollection<T>(typeof(T).FullName);
        return collection.FindAll().ToList<T>();
    }

    public static void InsertEntity<T>(T entity) where T : Entity
    {
        GetCollection<T>().Save(entity);
    }
}

then use it like this:

 public class SomeEntity : Entity { public string Name {set;get;} }

 MongoDB.InsertEntity<SomeEntity>(new SomeEntity(){ Name = "ashkan" });

 List<SomeEntity> someEntities = MongoDB.GetEntityList<SomeEntity>();
like image 90
Ashkan Ghodrat Avatar answered Jan 06 '23 17:01

Ashkan Ghodrat