Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

426
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda