Core Web API issues Related to Mongo DB - IMongoCollection<> could not be found AND System.FormatException at MongoDB.Bson.Serialization.BsonClassMapSerializer

 .NET Core and Mongo DB is a good bonding pair in Full Stack frame. Today, two issues I'm going to elaborate here and those two issues has been raised while developing Web API using .NET Core platform and use Mongo DB as backend.


Web API will call the Mongo DB and fetch the record, specific record, and able to update the record as well. Simple and straight forward. Build is successful. However, when I try to run this and actually test in browser, get the following error. Obvious this occurred at start up. Below the error.

Severity Code Description Project File Line Suppression State

Error CS0246 The type or namespace name 'IMongoCollection<>' could not be found (are you missing a using directive or an assembly reference?) MVCCoreApi MVCCoreApi\Services\MovieService.cs


One important note here, you should have MongoDb driver installed at your end so that you can add using MongoDB.Driver; in your project and work with IMongoCollection.

At the model page (Movie.cs), the additional length attributes attached with the ID. Removing the length attribute (I believe the length and ID type not matched as per Bson attributes) actually resolve this issue



Next Error: While trying to get specific movie while searching by the ID(kind of Object ID), as per the below screen, another error occurred while Execute. 



Error
System.FormatException: Element 'runtime' does not match any field or property of class MVCCoreApiMovie.Models.Movie.
   at MongoDB.Bson.Serialization.BsonClassMapSerializer`1.DeserializeClass(BsonDeserializationContext context)
   at MongoDB.Bson.Serialization.BsonClassMapSerializer`1.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
   at MongoDB.Bson.Serialization.IBsonSerializerExtensions.Deserialize[TValue](IBsonSerializer`1 serializer, BsonDeserializationContext context)
   at MongoDB.Driver.Core.Operations.CursorBatchDeserializationHelper.DeserializeBatch[TDocument](RawBsonArray batch, IBsonSerializer`1 documentSerializer, MessageEncoderSettings messageEncoderSettings)
   at MongoDB.Driver.Core.Operations.FindOperation`1.CreateFirstCursorBatch(BsonDocument cursorDocument)
   at MongoDB.Driver.Core.Operations.FindOperation`1.CreateCursor(IChannelSourceHandle channelSource, IChannelHandle channel, BsonDocument commandResult)
   at MongoDB.Driver.Core.Operations.FindOperation`1.ExecuteAsync(RetryableReadContext context, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Operations.FindOperation`1.ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken)
   at MongoDB.Driver.OperationExecutor.ExecuteReadOperationAsync[TResult](IReadBinding binding, IReadOperation`1 operation, CancellationToken cancellationToken)
   at MongoDB.Driver.MongoCollectionImpl`1.ExecuteReadOperationAsync[TResult](IClientSessionHandle session, IReadOperation`1 operation, ReadPreference readPreference, CancellationToken cancellationToken)
   at MongoDB.Driver.MongoCollectionImpl`1.UsingImplicitSessionAsync[TResult](Func`2 funcAsync, CancellationToken cancellationToken)
   at MongoDB.Driver.IAsyncCursorSourceExtensions.ToListAsync[TDocument](IAsyncCursorSource`1 source, CancellationToken cancellationToken)
   at MVCCoreApiMovie.Services.MovieService.GetAsync() in D:\Azure\MVCCoreApi\MVCCoreApi\Services\MovieService.cs:line 27
   at MVCCoreApi.Controllers.MoviesController.Get() in D:\Azure\MVCCoreApi\MVCCoreApi\Controllers\MoviesController.cs:line 22
   at lambda_method5(Closure, Object)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)


Get the idea from Mongo DB Developer portal - https://www.mongodb.com/developer/languages/csharp/using-linq-query-mongodb-dotnet-core-application/

Resolution: Put [BsonIgnoreExtraElements] on top of your model class (in my case it is Movie.cs)
                    [BsonIgnoreExtraElements]
                    public class Movie
                    {...

                 And, put [BsonRepresentation(BsonType.ObjectId)] on top if your property declaration
                 [BsonId]
                 [BsonRepresentation(BsonType.ObjectId)]
                 public string? Id { get; set; }

Finally, it start working...Now, search on specific id - "id": "5de24511185657a2f62d9e42"

To test this update the data against specific id -"id": "5de24511185657a2f62d9e42". And then update as below - adding Laha with director's name (hope the directors will forgive me for my silliness 😃 )

  "id": "5de24511185657a2f62d9e42",
  "title": "An American Tail: Fievel Goes West",
  "year": 1991,
  "rated": "G",
  "director": "Phil Nibbelink, Simon Wells, LAHA"



Now, to validate this, run the Web API /api/Movie/{id} - "id": "5de24511185657a2f62d9e42"



Revalidate this with Mongo DB...Aha my name is there!

Comments

Popular posts from this blog

How to fix Azure DevOps error MSB4126

How to create Custom Visuals in Power BI – Initial few Steps

How to fix Azure DevOps Error CS0579