【问题标题】:mongodb 2.0 query by discriminatormongodb 2.0 鉴别器查询
【发布时间】:2015-04-25 05:28:57
【问题描述】:

给定以下模型

[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();

【问题讨论】:

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


    【解决方案1】:

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

    目前,您可以使用“is”过滤器。

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

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

    【讨论】:

    • 谢谢克雷格——我在这里写的有趣的事情,我在基类中包含了 BsonDiscriminator 属性,但在我的实际代码中,我忘记了它——这当然会导致系统.FormatException 因为它试图反序列化同一集合中的 Contractor 实例。 (捂脸)
    猜你喜欢
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    相关资源
    最近更新 更多