Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

425
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda