skip to Main Content

I am simply trying to connect my MongoDB cluster with my .NET app, but when I test my routes with swagger i get this error:

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)

What I am trying to do is to add a simple item to my database to check my connection, and I am doing this within my Program.cs file so it does it only once.

Here are my files:

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>

Another error i started getting on my terminal whenever running the app is

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]

2

Answers


  1. Your project references

    • MongoDB.Driver version 3.0.0 and
    • MongoDB.EntityFrameworkCore version 8.0.0

    In version 3.0.0 of the driver, the GuidRepresentationMode property has been removed (per the release notes).

    MongoDB.EntityFrameworkCore expects a driver version of 2.25 and above, so that it thinks it can use v3.0 also, but fails when using properties that have been removed in v3.0.

    After an update of MongoDB.EntityFrameworkCore to version 8.2.0, this should be fixed.

    Login or Signup to reply.
  2. The error you’re encountering is likely due to a version mismatch between the MongoDB.Driver library and other components in your project, such as Microsoft.EntityFrameworkCore.MongoDB or related MongoDB/Bson libraries. Specifically, the error suggests that the GuidRepresentationMode method is being called but isn’t found, which indicates changes or deprecations in the MongoDB.Driver API.

    Here’s how you can troubleshoot and resolve this issue:

    CHECK MONGODB VERSION
    Ensure you are using a compatible version of the MongoDB.Driver. The GuidRepresentationMode property was introduced in MongoDB.Driver 2.7. If you’re using an older version of the library, upgrade it to the latest stable version compatible with your project.

    To check the installed version:

    Open the NuGet Package Manager or check your csproj file.
    Look for the MongoDB.Driver package and its version

    to update run this command in your bash terminal
    dotnet add package MongoDB.Driver –version <latest_version>

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search