Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

424
Views
Polymorphism using C# and MongoDB

I'm trying to use MongoDB for the first time using C#, but I'm struggling to implement polymorphism. A short summary of what I'm trying to achieve:

  • A project contains multiple Items
  • An Item can either be a Directory or a Bookmark
  • A Directory is a collection of other Directories or Bookmarks (Items)

I'm struggling with the second part. I used this as a reference, but whenever I try to get a project from the database, it contains a list of Items instead of either Bookmarks or Directories, and thus ignoring the Url of a Bookmark. I also found this Github repo which seems to accomplish the same thing, but I cannot implement it because I already have a .Find(). in my GetProjectByIdAsync method.

Any help is greatly appreciated!

Project.cs:

public class Project
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }
    public List<Item> Items { get; set; }
}

Item.cs:

[BsonIgnoreExtraElements(true)]
[BsonDiscriminator(RootClass = true)]
[BsonKnownTypes(typeof(Directory), typeof(Bookmark))]
public abstract class Item
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }
    public string Name { get; set; }}
}

Directory.cs:

public class Directory: Item 
{
     public List<Item> Items { get; set; }
}

Bookmark.cs:

public class Bookmark: Item
{
    public string Url { get; set; }
}

ProjectService.cs:

public async Task<Project> GetProjectByIdAsync(string id)
{
    return await _projects.Find(project => project.Id == id).FirstOrDefaultAsync();
}

The data does seem to be stored in the database in the correct way: enter image description here

over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!