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:
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:
