如何在 Mongo 3.1.0 c# 驱动中调用 FilterDefinition 的 Render 方法?

问题描述 投票:0回答:1

升级到 mongo c# 驱动程序 3.1.0 此代码不再编译:

public static BsonDocument ToBsonDocument<T>(this FilterDefinition<T> filter)
{
  var serializerRegistry = BsonSerializer.SerializerRegistry;
  var documentSerializer = serializerRegistry.GetSerializer<T>();
  return filter.Render(documentSerializer, serializerRegistry);
}

在上一版本中,Render 接受一个 RenderArgs 类型的参数

我尝试了这个,但收到错误:

参数 1:无法从 'MongoDB.Bson.Serialization.IBsonSerializer' 转换为 'string'

public static BsonDocument ToBsonDocument<T>(this FilterDefinition<T> filter)
{
  var serializerRegistry = BsonSerializer.SerializerRegistry;
  var documentSerializer = serializerRegistry.GetSerializer<T>();
  return filter.Render(new PathRenderArgs(documentSerializer, serializerRegistry));
}
mongodb-.net-driver .net-9.0
1个回答
0
投票

Render
类中最新的
FilterDefinition
方法不再支持两个参数,而是支持
RenderArgs<Document>
类型的参数。

public abstract class FilterDefinition<TDocument>
{
    public abstract BsonDocument Render(RenderArgs<TDocument> args);

   ...
}

并且从构造函数中,您可以提供

IBsonSerializer<TDocument>
IBsonSerializerRegistry
实例。

public record struct RenderArgs<TDocument>
{

    public RenderArgs(
        IBsonSerializer<TDocument> documentSerializer,
        IBsonSerializerRegistry serializerRegistry,
        PathRenderArgs pathRenderArgs = default,
        bool renderDollarForm = default,
        bool renderForFind = false,
        bool renderForElemMatch = false,
        ExpressionTranslationOptions translationOptions = null)
    {
        ...
    }

   ...
}

因此,修改

ToBsonDocument
方法如下:

public static BsonDocument ToBsonDocument<T>(this FilterDefinition<T> filter)
{
    var serializerRegistry = BsonSerializer.SerializerRegistry;
    var documentSerializer = serializerRegistry.GetSerializer<T>();
    return filter.Render(new RenderArgs<T>(documentSerializer, serializerRegistry));
}
© www.soinside.com 2019 - 2024. All rights reserved.