.NET应用连接MongoDB遇System.MissingMethodException问题求助
错误信息
通过Swagger测试路由时抛出:
System.MissingMethodException: Method not found: 'MongoDB.Bson.GuidRepresentationMode MongoDB.Bson.BsonDefaults.get_GuidRepresentationMode()'.
at MongoDB.Driver.MongoUrlBuilder..ctor()
at MongoDB.Driver.MongoUrlBuilder..ctor(String url)
at Microsoft.EntityFrameworkCore.MongoOptionsExtension.SanitizeConnectionStringForLogging(String connectionString)
at Microsoft.EntityFrameworkCore.MongoOptionsExtension.WithConnectionString(String connectionString)
at Microsoft.EntityFrameworkCore.MongoDbContextOptionsExtensions.UseMongoDB(DbContextOptionsBuilder optionsBuilder, String connectionString, String databaseName, Action1 optionsAction)
运行应用时终端额外提示:
The type 'IMongoClient' is defined in an assembly that is not referenced. You must add a reference to assembly 'MongoDB.Driver, Version=2.25.0.0, Culture=neutral, PublicKeyToken=null'. [/Users/rakibulb/Documents/ComputerScience/PortfolioProjects/Web/book-management/backend/backend.csproj]
我希望通过在Program.cs中添加一次性测试条目到数据库来验证连接,以下是相关代码文件:
相关代码文件
Program.cs
using backend.Data; using Microsoft.EntityFrameworkCore; using backend.Models; using MongoDB.Driver; var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllersWithViews(); var mongoDBSettings = builder.Configuration.GetSection("MongoDBSettings").Get<MongoDBSettings>() ?? throw new InvalidOperationException("MongoDBSettings section is not configured"); builder.Services.Configure<MongoDBSettings>(builder.Configuration.GetSection("MongoDBSettings")); builder.Services.AddDbContext<ApplicationDBContext>(options => options.UseMongoDB(mongoDBSettings.AtlasURI, mongoDBSettings.DatabaseName)); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.MapPost("/api/test-book", async (ApplicationDBContext context) => { try { var testBook = new Book { Title = "Test Book", Author = "Test Author", Pages = 100 }; context.Books.Add(testBook); await context.SaveChangesAsync(); return Results.Ok(new { message = "Test book added successfully", book = testBook }); } catch (Exception ex) { return Results.BadRequest(new { message = $"Error adding book: {ex.Message}" }); } }); // You can also add a GET endpoint to verify the book was added app.MapGet("/api/test-book", async (ApplicationDBContext context) => { var books = await context.Books.ToListAsync(); return Results.Ok(books); }); app.Run(); // MongoDB password : 6F1uj59S9WzSkbfK
backend.csproj
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>net8.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.4" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.4"> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.4"> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> <PackageReference Include="MongoDB.Bson" Version="3.0.0" /> <PackageReference Include="MongoDB.Driver" Version="3.0.0" /> <PackageReference Include="MongoDB.Driver.Core" Version="2.30.0" /> <PackageReference Include="MongoDB.EntityFrameworkCore" Version="8.0.0" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" /> </ItemGroup> </Project>
解决方案
1. 统一MongoDB相关包版本
问题根源是MongoDB各组件版本不兼容:MongoDB.Bson/MongoDB.Driver用了3.0.0,MongoDB.Driver.Core是2.30.0,而MongoDB.EntityFrameworkCore 8.0.0要求MongoDB驱动版本至少为2.25.0。修改backend.csproj中的包引用,统一所有MongoDB相关包的版本:
<PackageReference Include="MongoDB.Bson" Version="2.25.0" /> <PackageReference Include="MongoDB.Driver" Version="2.25.0" /> <PackageReference Include="MongoDB.Driver.Core" Version="2.25.0" /> <PackageReference Include="MongoDB.EntityFrameworkCore" Version="8.0.0" />
2. 清理重建项目
- 删除项目目录下的
bin和obj文件夹 - 执行命令
dotnet restore恢复依赖 - 执行命令
dotnet build重新构建项目
3. 一次性测试数据插入优化
如果要在应用启动时仅执行一次测试数据插入,无需通过API接口,可调整Program.cs:
var app = builder.Build(); // 启动前添加一次性测试数据 using (var scope = app.Services.CreateScope()) { var context = scope.ServiceProvider.GetRequiredService<ApplicationDBContext>(); // 避免重复插入 if (!await context.Books.AnyAsync(b => b.Title == "Test Book")) { var testBook = new Book { Title = "Test Book", Author = "Test Author", Pages = 100 }; context.Books.Add(testBook); await context.SaveChangesAsync(); Console.WriteLine("Test book added successfully"); } } // 后续中间件配置...
内容的提问来源于stack exchange,提问作者RakibulB

