简体   繁体   English

MongoDB C# 驱动程序 2.1.0 - 解析参考

[英]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.我正在按照教程使用以下代码段从 MongoDbRef 解析项目负责人。 Unfortunately i cannot find something that resembles something like the FetchDBRefAs<>() method in the C# 2.1.0 Driver for MongoDB不幸的是,我在 C# 2.1.0 Driver for MongoDB 中找不到类似于 FetchDBRefAs<>() 方法的东西

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?有人可以向我解释这如何与 2.1.0 驱动程序配合使用吗?

I solved it by writing my own extension method for IMongoDatabase.我通过为 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();
}

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

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