Skip to main content
 首页 » 编程设计

c#之尝试使用 .Net Core 3.0 (MongoDB.Driver 2.8.0) 获取对 MongoDB 集合的引用时出现异常

2024年02月04日32zdz8207

我的环境:

Microsoft.NETCore.Platforms (3.0.0-preview5.19224.8)

MongoDB.Driver (2.8.0)

我的问题:

在更新“Microsoft.NETCore.Platforms”版本之前,以下代码运行良好:

//Collection of resales 
public IMongoCollection<Revenda> CollRevendas; 
 
public BaseRepository(IConfiguration config) 
{ 
    try 
    { 
        // Location of the database, configured in the "appsettings.json" file 
        var client = new MongoClient(config.GetConnectionString("Config.api.mstiDFE")); 
 
        // Name of the database 
        Database = client.GetDatabase("api_mstiDFE_II"); 
 
        // Get the reference for the collection "Resales" 
        CollRevendas = Database.GetCollection<Revenda>("Revendas"); 
 
    } 
    catch (System.Exception ex) 
    { 
        throw; 
    } 
 
} 

更新后,当尝试执行“CollRevendas = Database.GetCollection("Revendas");"语句,抛出以下异常:

{“'MongoDB.Bson.Serialization.BsonClassMap' 的类型初始值设定项抛出异常。”}

使用以下堆栈跟踪:

System.TypeInitializationException: The type initializer for 'MongoDB.Bson.Serialization.BsonClassMap' threw an exception. ---> System.ArgumentNullException: Value cannot be null. 
Parameter name: type 
at System.Reflection.IntrospectionExtensions.GetTypeInfo(Type type) 
at MongoDB.Bson.Serialization.BsonClassMap..cctor() 
--- End of inner exception stack trace --- 
at MongoDB.Bson.Serialization.BsonClassMap.LookupClassMap(Type classType) 
at MongoDB.Bson.Serialization.BsonClassMapSerializationProvider.GetSerializer(Type type, IBsonSerializerRegistry serializerRegistry) 
at MongoDB.Bson.Serialization.BsonSerializerRegistry.CreateSerializer(Type type) 
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) 
at MongoDB.Bson.Serialization.BsonSerializerRegistry.GetSerializer[T]() 
at MongoDB.Driver.MongoCollectionImpl`1..ctor(IMongoDatabase database, CollectionNamespace collectionNamespace, MongoCollectionSettings settings, ICluster cluster, IOperationExecutor operationExecutor) 
at MongoDB.Driver.MongoDatabaseImpl.GetCollection[TDocument](String name, MongoCollectionSettings settings) 
at api.mstiDFE.Infra.Repositories.BaseRepository..ctor(IConfiguration config) in C:\Users\Source\Workspace\api.mstiDFE\api.mstiDFE\Infra\Repositories\BaseRepository.cs:line 27 

不幸的是,我无法降级“Microsoft.NETCore.Platforms”。所以任何提示都将非常受欢迎。

请您参考如下方法:

MongoDB Driver for C# 2.8.1 版已于昨天(05-15-19)发布。 提出这个问题后不久,我在以下链接中获得了信息:

CSHARP-2595: Fix initialization on .NET Core 3.0 preview 4.

升级到2.8.1版本后,问题解决。

所以我会把问题留在这里,因为它可以为有同样问题的其他人服务。