将C#MongoDB LINQ与鉴别符一起使用 [英] Using C# MongoDB LINQ with discriminator
问题描述
我有一个单一的MongoDB集合,其中包含三个不同类(A,B,C)的文档,这些文档都继承自相同的类D.
I have a single MongoDB collection holding documents of three different classes (A,B,C) which all inherit from a common class D.
使用正式的C#驱动程序,我插入了所有三种类型(A,B,C)的文档,并且它们都正确地显示了_t鉴别符,并且在我的代码中注册了它们的类映射.
Using the official C# driver, I have inserted documents of all three types (A,B,C) and they all appear correctly with the _t discriminator, and in my code their class maps are registered.
如果我发出如下所示的LINQ查询(使用VB):
If I issue a LINQ query such as the following (using VB):
dim Result = database.GetCollection("mycol").AsQueryable(Of C).Where(some where clause)
如果我计算得出的结果,则会收到错误消息元素'来自类A的元素名称'与类C的任何字段或属性都不匹配."
If I count the results of this, I am getting an error "Element 'an element name from class A' does not match any field or property of class C."
识别符不是要在AsQueryable(Of C)
代码中插入吗?看来,当我发出.Count
时,我的Where子句(特定于C类的元素)将应用于A,B和C的文档.
Isn't the discriminator meant to kick in here in the AsQueryable(Of C)
code? It appears that when I issue .Count
my Where clause, which is specific to elements of class C, is being applied to documents of A,B, and C.
我尝试添加.OfType(Of C)
无效,尝试使用.ToList
首先转换为列表,但是我仍然遇到相同的错误.有任何想法吗?
I have tried adding .OfType(Of C)
with no effect, have tried converting to a List first with .ToList
, but I continue to get the same error. Any ideas?
作为背景,我的客户代码通常将处理类型D的对象.A,B,C共享许多从D继承的通用属性,因此我希望将它们放在索引上,因此将它们放在单个集合中.但是,在特殊情况下,有时我需要直接引用类型为A,B或C的对象.
As background, my client code will usually deal with objects of type D. A, B, C share a lot of common properties inherited from D which I want to put indexes on, hence I put them in a single collection. However, occassionally I need to directly reference an object of types A, B, or C in special circumstances.
推荐答案
在使用多态类型层次结构时,您的集合变量和LINQ查询应从基类开始.例如,要从数据库中读取所有类型为A的文档,您应编写:
When working with a polymorphic type hierarchy your collection variable and your LINQ queries should start in terms of the base class. For example, to read all the documents of type A back from the database you would write:
var collection = database.GetCollection<D>("mycol");
var query = collection.AsQueryable<D>().OfType<A>();
foreach (var a in query)
{
// process document of type A
}
出于诊断目的,您可以使用以下命令查看相应的本机MongoDB查询:
For diagnostic purposes you can see the corresponding native MongoDB query using:
var json = ((MongoQueryable<A>)query).GetMongoQuery().ToJson();
请注意,由于OfType()调用更改了IQueryable的类型,因此必须将查询强制转换为MongoQueryable< A>(而不是MongoQueryable< D>).
Note that you have to cast query to a MongoQueryable<A> (not MongoQueryable<D>) because the OfType() call changed the type of the IQueryable.
这篇关于将C#MongoDB LINQ与鉴别符一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!