I am new to Mongo and have a project that uses the C# MongoDb driver and Linq for retrieving data from MongoDb.
I have an object named Instance
that I retrieve from the Mongo collection just fine. However, the object's Template
property belongs in a separate collection and is null when querying the Instance collection. I would like to eager load the template data when querying the instance.
This would be the equivalent of Entity Framework's Include
method which eager loads related entities. I have searched the net for an equivalent approach using the C# Mongo driver but no luck.
How can I accomplish this using the C# MongoDb driver and Linq?
public class Instance
{
public int Id { get; set; }
public string Name { get; set; }
public int? TemplateId { get; set; }
public Template Template { get; set; }
}
public class Template
{
public int Id { get; set; }
public string Name { get; set; }
}
var collection = MongoDatabase.GetCollection<Instance>("Instances").AsQueryable()
var instance = collection.First(i => i.Id == 1);
var template = instance.Template; //always null