[英]Modify Insert for general use
您好,在编写此插入到 MongoDB 时,使用名为Game
的 class 通过以下代码完成。
var games = database.GetCollection<Game>("Games");
Game newGame = new Game()
{
Name = "Monopoly",
Price = 22,
Category = "Board Game"
};
games.InsertOne(newGame);
我正在尝试创建一个将这些作为参数的 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");
但我想将这个 function 用作通用插入 function:
MyClass1 c1=new MyClass1();
//...properties etc
insert(c1, "MyClass1");
MyClass2 c2=new MyClass2();
//...properties etc
insert(c2,"MyClass2");
我应该如何修改插入方法以便它接受任何给定的 class 并将其插入到给定的 MongoDB 集合中?
void insert(object obj, string collection)
{
//...code to get obj's class?
var mongoObject = database.GetCollection<obj_class>(collection);
mongoObject.InsertOne(game);
}
您可以修改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.