简体   繁体   English

C# MongoDb驱动包括子object

[英]C# MongoDb driver include child object

I am new to Mongo and have a project that uses the C# MongoDb driver and Linq for retrieving data from MongoDb.我是 Mongo 的新手,并且有一个项目使用C# MongoDb 驱动程序和 Linq 从 ZC13D2009A3AAE2AB 检索数据。

I have an object named Instance that I retrieve from the Mongo collection just fine.我有一个名为Instance的 object ,我可以从 Mongo 集合中检索到它。 However, the object's Template property belongs in a separate collection and is null when querying the Instance collection.但是,对象的Template属性属于单独的集合,在查询 Instance 集合时为 null。 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.这相当于 Entity Framework 的Include方法,它急切地加载相关实体。 I have searched the net for an equivalent approach using the C# Mongo driver but no luck.我已经在网上搜索了使用 C# Mongo 驱动程序的等效方法,但没有运气。

How can I accomplish this using the C# MongoDb driver and Linq?如何使用 C# MongoDb 驱动程序和 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

You can have Typed Lookup like this>您可以像这样进行类型查找>

public class Instance
{
    public ObjectId Id { get; set; }
    public string Name { get; set; }
    public ObjectId TemplateId { get; set; }
    public Template Template { get; set; }
}

public class Template
{
    public ObjectId Id { get; set; }
    public string Name { get; set; }
}


string connectionString = "mongodb://localhost:27017";
var client = new MongoClient(connectionString);

var db = client.GetDatabase("test");
var instances = db.GetCollection<Instance>("Instances");
var resultOfJoin = instances.Aggregate()
    .Lookup("Templates", "TemplateId", "_id", @as: "Template")
    .Unwind("Template")
    .As<Instance>()
    .ToList();

EDIT: Unwind part edited by jcruz.编辑:展开 jcruz 编辑的部分。

For eager load Try using对于急切的负载尝试使用

public virtual Template Template { get;公共虚拟模板模板 { 获取; set;放; } in instance. } 例如。 But still you have to use Include() if you want to retrieve the data from child table,但是如果你想从子表中检索数据,你仍然必须使用 Include(),

You can get templateid from the instance which should have PK of tempalte without include您可以从应该具有模板 PK 的实例中获取模板 ID,而无需包含

Tested for EF Core 6.3已针对 EF Core 6.3 测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM