简体   繁体   English

修改插入以供一般使用

[英]Modify Insert for general use

Hello as of writing this inserting to MongoDB is done with the following code using a class named Game .您好,在编写此插入到 MongoDB 时,使用名为Game的 class 通过以下代码完成。

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:我正在尝试创建一个将这些作为参数的 function:

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:但我想将这个 function 用作通用插入 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?我应该如何修改插入方法以便它接受任何给定的 class 并将其插入到给定的 MongoDB 集合中?

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:您可以修改Insert方法以支持泛型类型,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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