Filtering in mongo by interface

316 Views Asked by At

I have a mongo collection that I want to type to an interface. It should be able to contain multiple concrete types, all of which implement this interface. However when making queries if I use the interface it tells me that it cannot find serialization information. Sample code:

var collection = database.GetCollection<ITestInterface>("TestCollection2");
var filter = Builders<ITestInterface>.Filter.Eq(x => x.Number, 42);
var items = collection.FindSync(filter);

This results in an exception with message: "Unable to determine the serialization information for x => x.Number."

Is there a way to tell the drivers how to serialize things on an interface? I can find a workaround that requires all my types to have a common baseClass and then I can do something like:

var filter = Builders<BaseClass>.Filter.Eq(x => x.Number, 42);
var items = collection.OfType<BaseClass>().FindSync(filter);

However, I would rather not do this and instead get the drivers to be able to find the serialization information it needs for interfaces.

So is there a way to tell the drivers how to serialize things on an interface or otherwise get the first block of code to work?

0

There are 0 best solutions below