小编Ste*_*e H的帖子

使用 MongoDB C# 驱动程序查询派生类型值

我正在从旧的旧版 MongoDB 驱动程序移植一些代码以使用新驱动程序,但遇到了问题。我有一个集合,其中包含来自公共基类的多个派生类型。以前,我能够使用派生类属性查询集合(使用基类型声明)并仅检索派生类文档。因此,鉴于这些课程:

[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; }
}
Run Code Online (Sandbox Code Playgroud)

然后我可以做类似的事情:

MongoCollection<Animal> animals = db.GetCollection<Animal>("Animals");
var q = Query<Cat>.EQ(c => c.LikesFish, true);
var catsThatLikeFish = animals.FindAs<Animal>(q).ToList();
Run Code Online (Sandbox Code Playgroud)

效果很好。

但是现在我必须输入过滤器并且无法再编译:

IMongoCollection<Animal> animals = db.GetCollection<Animal>("Animals");
var query = Builders<Cat>.Filter.Eq(c …
Run Code Online (Sandbox Code Playgroud)

.net c# mongodb mongodb-.net-driver

3
推荐指数
1
解决办法
3409
查看次数

标签 统计

.net ×1

c# ×1

mongodb ×1

mongodb-.net-driver ×1