MongoDB C#创建一个函数,我可以将类型/类名称作为参数传递给它

时间:2017-01-09 19:31:27

标签: c# mongodb types mongodb-.net-driver

我有一个功能(见下文)。

它非常适合我需要它做的事情,除了这两行之外,我还有另一个几乎完全相同的东西:

        var collection = MongoDB.GetCollection<RocketRequest>("RocketRequest");

        var filter = Builders<RocketRequest>.Filter.Eq("RocketRequestId", 4);

我希望能够以某种方式使函数动态化,所以我可以传递它,所以我可以将这个相同的函数用于多个目的/类型,而不需要为每一个创建一个新函数。

对于上面两行,我想看看是否有可能以某种方式将集合中的对象作为参数传递给函数?

或者最坏的情况是有一个switch语句来检查我传递的字符串值,如果是这样,将其设置为,否则将其设置为其他值。这样做的问题是我无法在switch语句中创建变量,如果我尝试在switch之外创建它我必须将它作为一个空对象(然后将集合设置为我在交换机内需要的内容)而且我可以也没办法。

       public static int MongoReadData(string[] MongoListOfFieldsToDisplay)
    {
        int CountRecords = 0;

        // create connection TO MongoDB
        MongoClient MongoClientConn = new MongoDatabaseConnection().mongoConn();
        var MongoDB = MongoClientConn.GetDatabase("Viper");
        var collection = MongoDB.GetCollection<RocketRequest>("RocketRequest");

        var filter = Builders<RocketRequest>.Filter.Eq("RocketRequestId", 4);
        //var filter = Builders<RocketRequest>.Filter.Empty;
        var result = collection.Find(filter).ToListAsync().Result;

        // do here so it is after the filtering
        CountRecords = Convert.ToInt32(collection.Find(filter).Count());

        return CountRecords;

    }// end MongoReadData    

2 个答案:

答案 0 :(得分:1)

如果我明白你想要什么,你可以尝试一下:

public IEnumerable<T> GetMongoData<T>(string collectionName, 
                            Expression<Func<T,bool>> filter)
{
    MongoClient MongoClientConn = new MongoDatabaseConnection().mongoConn();
    var MongoDB = MongoClientConn.GetDatabase("Viper");
    var collection = MongoDB.GetCollection<T>(collectionName);

    return collection.Find(filter).ToEnumerable();
}

使用示例:

var items=GetMongoData<TestItem1>("test1", t=>t.Points>10);
var items2=GetMongoData<TestItem2>("test2", t=>t.Name.Contains("a"));

答案 1 :(得分:0)

我能够找到允许我将该类作为NEW传递给代码的代码,以使其能够完成我需要的工作。请参阅该功能的新版本和通话:

所以我调用相同的函数,可以用它来查询2个独立的集合。

find /var/www/html/*/app -name database.php -print