问题升级到最新的 C# MongoDB 驱动程序

Issue upgrading to latest C# MongoDB Driver

我有一个使用 MongoDB 的 .NET 应用程序,所以我使用 mongo c# 驱动程序。我使用的当前版本是 1.9.2.

我正在尝试将其更新到最新的 C# mongodb 驱动程序 - 2.7.0。到目前为止,我不得不进行大量代码更改以进行重大更改。我现在被一些问题难住了 - 可能会在适当的时候向其他人提出新问题,但下面的问题导致应用程序在调试时甚至无法加载。

这是我使用 1.9.2 驱动程序的原始代码:

    /// <summary>
    /// Since the current Mongo driver does not support database side Select
    /// projections, we need to use this custom function to achieve the same.
    /// </summary>
    /// <param name="criteria"></param>
    /// <param name="fields"></param>
    /// <returns></returns>
    public IEnumerable<T> Get(Expression<Func<T, bool>> criteria,
        params Expression<Func<T, object>>[] fields)
    {
        return this.Collection.FindAs<T>(Query<T>.Where(criteria)).SetFields
                 (Fields<T>.Include(fields));
    }

这是我尝试使用最新的 C# 驱动程序的结果:

    /// <summary>
    /// Since the current Mongo driver does not support database side Select
    /// projections, we need to use this custom function to achieve the same.
    /// </summary>
    /// <param name="criteria"></param>
    /// <param name="fields"></param>
    /// <returns></returns>
    public IEnumerable<T> Get(Expression<Func<T, bool>> criteria,
        params Expression<Func<T, object>>[] fields)
    {
        return this.Collection.Find<T>(criteria).Project(Builders<T>.Projection.Include(FilterDefinitionBuilder<T>.(fields)));
    }

但是我在 .(fields))) 上收到了一个红色的构建错误。说出不正确的主要表达,但不确定正确的解决方法是什么。

更新

我在下面添加了来自 mickl answer 的代码,现在当 运行 应用程序出现以下异常时:

"An error occurred while deserializing the Id property of class MyApp.Domain.Models.EntityBase: Cannot deserialize a 'String' from BsonType 'ObjectId'."

我有一个 BsonClassRegistration class 和我的旧 C# 驱动程序 Mongo 代码 - 其中的原始代码如下:

        BsonClassMap.RegisterClassMap<EntityBase>(cm =>
        {
            cm.AutoMap();
            cm.SetIdMember(cm.GetMemberMap(x => x.Id).SetIdGenerator(StringObjectIdGenerator.Instance));
            cm.GetMemberMap(c => c.Id).SetRepresentation(BsonType.ObjectId);
        });

为了通过升级到最新的 C# 驱动程序来解决这个问题,我将代码更改为以下内容:

        BsonClassMap.RegisterClassMap<EntityBase>(cm =>
        {
            cm.AutoMap();
            cm.SetIdMember(cm.GetMemberMap(x => x.Id).SetIdGenerator(StringObjectIdGenerator.Instance));
            cm.GetMemberMap(c => c.Id).SetSerializer(new StringSerializer(BsonType.ObjectId));
        });

这是我现在在 Get 方法中看到的失败的原因吗

您可以像您尝试的那样使用 Builders<T>.Projection,但您必须动态构建 ProjectionDefinition<T> 实例,可以像下面那样完成:

public IEnumerable<T> Get(Expression<Func<T, bool>> criteria, params Expression<Func<T, object>>[] fields)
{
    var find = Collection.Find<T>(criteria);

    var builder = Builders<T>.Projection;
    var definition = (ProjectionDefinition<T>)null; 

    foreach(var field in fields)
    {
        definition = definition?.Include(field) ?? builder.Include(field);
    }

    if (definition == null) return find.ToList();

    return find.Project<T>(definition).ToList();
}