mongodb 2.0 鉴别器查询

mongodb 2.0 query by discriminator

给定以下模型

[BsonDiscriminator(RootClass = true)]
[BsonKnownTypes(typeof(Employee), typeof(Contractor)]
public class Person
{
    public ObjectId Id {get;set;}
    public string Name {get;set;}
}
public class Employee : Person
{
    public double Salary {get;set;}
}    
public class Contractor : Person
{
    public double DailyRate {get;set;}
}

使用旧版驱动程序,我可以执行以下操作来获取所有承包商的列表。

var employees = database.GetCollection("people").AsQueryable<Employee>().OfType<Employee>();

目前 2.0 驱动程序不支持 AsQueryable()(应该在 2.1 中支持)所以与此同时,我对如何构建合适的过滤器有点不知所措从集合中选择所有承包商

var list = await collection.Find(filter).ToListAsync();

相关功能请求在这里:https://jira.mongodb.org/browse/CSHARP-1194

现在,您可以使用 "is" 过滤器。

collection.Find(x => x is Employee).ToListAsync();

您仍然需要在最后转换为 Employee,但它们都会根据注册的鉴别器进行过滤。