简体   繁体   中英

Modify Insert for general use

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);
}

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM