假设模型为
[BsonDiscriminator(RootClass = true)]
[BsonKnownTypes(typeof (Dog), typeof (Cat))]
class Animal
{
public ObjectId Id {get;set;}
public string Name {get;set;}
}
class Dog : Animal { public int BarkVolume {get;set;} }
class Cat : Animal { public int PurrVolume {get;set;} }
我可以执行以下操作:
var collection = new MongoClient().GetServer().GetDatabase("test").GetCollection<Animal("Animals");
collection.Save( new Dog { Name="spot", BarkVolume=7 } );
collection.Save( new Cat { Name="kitty", PurrVolume=2 } );
但是,如果我然后尝试仅查询猫
var cats = collection.AsQueryable<Cat>();
foreach(var c in cats)
{
Console.WriteLine("{0} purrs at {1}", c.Name, c.PurrVolume);
}
我会收到异常“Element BarkVolume 与 Cat 类的任何字段或属性不匹配”。
当然,如果我将查询更改为:
var cats = collection.AsQueryable<Cat>().Where(x=>x is Cat);
那么没问题,但是会出现一个警告,指出 x is Cat 始终为 true。
驱动程序不对鉴别器注入(inject)测试是否有特殊原因_t
最佳答案
这是一个设计决策(经过一段时间的工作后,我同意这一点)。要指定 _t
过滤器,您可以使用 OfType
扩展方法,该方法比 x => x is Cat
更清晰。
在 MongoDB C# 驱动程序中,几乎所有内容都有类型化和非类型化选项。输入的选项只是为了方便起见,它们不会改变结果查询。当您真正关心查询性能和索引利用率时,这是一件好事。
例如,如果您仅使用特定类型的属性进行查询,则无需添加 OfType
(以及生成的 _t
过滤器),并且如果您执行查询引擎可能会使用您可能不希望它执行的 _t
索引。
关于c# - 为什么 AsQueryable<T> 不暗示 _t 鉴别器上的过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27172403/