Search code examples
c#mongodbmongodb-.net-driver

MongoDB C# Driver 2.1.0 - resolve reference


I have the following relationships between classes:

public class Person : Entity
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Project : Entity
{
    public string ProjectName { get; set; }
    public MongoDBRef Leader { get; set; }
}

I was following this tutorial to resolve the project leader from the MongoDbRef by using the following snippet. Unfortunately i cannot find something that resembles something like the FetchDBRefAs<>() method in the C# 2.1.0 Driver for MongoDB

var projectCollection = this.Database.GetCollection<Project>("Projects");
var query = from p in projectCollection.AsQueryable<Project>()
            select p;

foreach (var project in query)
{
    Console.WriteLine(project.ProjectName);
    if(project.Leader != null)
    {
        // can't figure this out since 
        // database.FetchDBRefAs<T>(...) is not available anymore
    }
}

Can someone explain to me how this works with the 2.1.0 Driver?


Solution

  • I solved it by writing my own extension method for IMongoDatabase. So in case anybody else stumbles across this problem, this might be helpful:

    public static async Task<T> FetchDBRef<T>(this IMongoDatabase database, MongoDBRef reference) where T : Entity
    {
        var filter = Builders<T>.Filter.Eq(e => e.Id, reference.Id.AsString);
        return await database.GetCollection<T>(reference.CollectionName).Find(filter).FirstOrDefaultAsync();
    }