我移植從舊的遺留MongoDB的司機一些代碼,使用新的驅動程序,並已觸及問題查詢派生類型的值。我有一個包含來自公共基類的多個派生類型的集合。以前,我能夠使用派生類屬性查詢集合(這是使用基類型聲明的),並只檢索派生類文檔。所以考慮到這些類:使用MongoDB的C#驅動
[BsonDiscriminator(RootClass = true)]
[BsonKnownTypes(typeof(Cat),typeof(Dog))]
class Animal
{
[BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
public string Id { get; set; }
public string Name { get; set; }
}
class Cat : Animal
{
public bool LikesFish { get; set; }
}
class Dog : Animal
{
public string FavouriteBone { get; set; }
}
然後我可以這樣做:
MongoCollection<Animal> animals = db.GetCollection<Animal>("Animals");
var q = Query<Cat>.EQ(c => c.LikesFish, true);
var catsThatLikeFish = animals.FindAs<Animal>(q).ToList();
它工作得很好。
但是現在我必須輸入濾波器,不能再編譯:
IMongoCollection<Animal> animals = db.GetCollection<Animal>("Animals");
var query = Builders<Cat>.Filter.Eq(c => c.LikesFish, true);
var catsThatLikeFish = animals.FindSync(query);
,並得到這個錯誤:可能
Error CS0411 The type arguments for method 'IMongoCollection<Animal>.FindSync<TProjection>(FilterDefinition<Animal>, FindOptions<Animal, TProjection>, CancellationToken)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
這是不再使用新的驅動程序?我們有類允許通用查詢這個集合,我現在看不到任何優雅的方法。
編輯:
可悲的是獨立的集合是我們混合過濾器表達式拉回使用相同的查詢不同類型的非首發。在「貓狗」例如從上面這樣的:
var catQuery = Query<Cat>.EQ(c => c.LikesFish, true);
var dogQuery = Query<Dog>.EQ(c => c.FavouriteBone, "Beef");
var q = Query.Or(catQuery, dogQuery);
var catsThatLikeFishOrDogsThatLikeBeef = animals.FindAs<Animal>(q).ToList();
我會看看「nameof」上述方法 - 可工作,但它似乎的老辦法優雅缺乏給我。 ..
任何幫助,非常感謝!
感謝,
史蒂夫
除了Maksim的回答下面,在新API中有一個OfType()方法... IMongoCollection dogs = db.GetCollection (「Animals」)。OfType ()。 –