Home > Software design >  Modify Insert for general use
Modify Insert for general use

Time:12-31

Hello as of writing this inserting to MongoDB is done with the following code using a class named Game.

var games = database.GetCollection<Game>("Games"); 
Game newGame = new Game() 
{
    Name = "Monopoly",
    Price = 22, 
    Category = "Board Game" 
}; 
games.InsertOne(newGame);

I am trying to create a function that takes these as parameters:

void insert(Game game, string collection)
{
    var games = database.GetCollection<Game>(collection);
    games.InsertOne(game);
}
// use would be like
Game game=new Game();
//...properties etc

test(game,"Games");

But I would like to use this function as a general-purpose insert function:

MyClass1 c1=new MyClass1();
//...properties etc

insert(c1, "MyClass1");

MyClass2 c2=new MyClass2();
//...properties etc

insert(c2,"MyClass2");

How should I modify the insert method so it accepts any given class and inserts it into the given MongoDB collection?

void insert(object obj, string collection)
{
    //...code to get obj's class?

    var mongoObject = database.GetCollection<obj_class>(collection);
    mongoObject.InsertOne(game);
}

CodePudding user response:

You can modify the Insert method to support the generic type as below:

void Insert<T>(T obj, string collectionName) where T : new()
{
    var collection = database.GetCollection<T>(collectionName);
    collection.InsertOne(obj);
}
  • Related