MongoDB problem reading from database using interface

Hi @Carlos_Saraiva1

I think I’m still missing a little bit of context here, regarding exactly how your classes and collections are defined, but I think that the issue here is that you’ve created a parametrized collection using an interface, something like

_collection = db.GetCollection<IAccount>("accounts");

You’re correct that in this case the best course of action is to use a base class, so in this case you could do something like:

  [BsonKnownTypes(typeof(DebitCard), typeof(CreditCard))]
  public class Card : IAccount
  {
      public virtual string Type { get; set; }
      public Guid Id { get; set; }
      public Guid? TenantId { get; set; }
      public string Name { get; set; } = string.Empty;

      public decimal Balance { get; set; }
  }

  public class DebitCard : Card
  {
      public override string Type { get; set; } = "DebitCard";
  }

  public class CreditCard : Card
  {
      public override string Type { get; set; } = "CreditCard";
  }

And then define your collection on the base class:

_collection = db.GetCollection<Card>("cards");

With this you should be able to filter the collection as you please. Remeber, when you’re working with polymorphic objects, you should always create the collection with the “most generic type” you have, and then eventually filter it (in this case Card). If you create your collection with a more specific type (like CreditCard in this case), you could get errors.
For instance:

_collection.OfType<CreditCard>().Find(filter).FirstOrDefault()

I hope this answers your questions.

2 Likes