4

Using C# MongoDB LINQ with discriminator describes exacty what I am trying to do, but I am trying to use the new official 2.0.1 driver.

I have a series of subclasses with their specialised properties all inheriting from a base class containing common properties. Discriminator attributes seem fine and I have successfully saved a mixture of documents using the subtypes.

What I expected to be able to do next was a query similar to:

  var subsetB = db.GetCollection<BaseClass>("Documents").AsQueryable<BaseClass>().OfType<SubclassB>();

To get all the documents of type SubclassB. However, the AsQueryable() and OfType() methods mentioned in the documentation and articles I have found don't seem to be available.

Have I missed something or is there an alternative recommended method of achieving this with the new driver?

Community
  • 1
  • 1
Bob Gear
  • 174
  • 1
  • 3
  • 13

2 Answers2

4

There's no special support for that.

You need to explicitly add a filter for the discriminator field, _t.

var results = await collection.Find(Builders<SubclassB>.Filter.Eq("_t", nameof(SubclassB))).ToListAsync();
i3arnon
  • 113,022
  • 33
  • 324
  • 344
  • Thanks for this - you helped me solve the basic problem. However, would I be better off, for the time being using the version 1 driver because that seems to be covered by lots of examples, blog posts etc. I'm finding the v2 Driver with its asynchronous programming model really hard to get to grips with as a newcomer to MongoDB as well. I would welcome a recommendation on this. – Bob Gear Aug 24 '15 at 15:48
  • @BobGear well, that really depends on you. The old one is deprecated and it doesn't support async-await. If you don't care about that I guess you can wait before moving up until there's more info around. There are also free online MongoDB courses you can take. – i3arnon Aug 24 '15 at 18:11
1

This seems to work for me in the latest version of the drivers:

var results = await GetCollection<BaseClass>("Documents").OfType<SubClass>.Find(...);
Ilya Chernomordik
  • 27,817
  • 27
  • 121
  • 207