aspnetrun/run-aspnetcore-microservices

InvalidOperationException in GetProductByCategory

viniciusdesa opened this issue · 2 comments

Hi,

I followed the course with all the steps from version 3.1 until the video 22. Developing Presentation Layer - Create CatalogController Class for Catalog.API.
When I opened the course today, I realized that you updated the videos to .Net 5. I followed them in order to make it compatible (added Swashbuckle support, made some minor changes in Startup.cs and tried to run as you indicated).
When I run the microservice, it opens and the methods work except GetProductByCategory. It returns the following Exception:

An unhandled exception has occurred while executing the request.
      System.InvalidOperationException: The serializer for field 'Category' must implement IBsonArraySerializer and provide item serialization info.
         at MongoDB.Driver.ElementMatchFilterDefinition`2.Render(IBsonSerializer`1 documentSerializer, IBsonSerializerRegistry serializerRegistry)
         at MongoDB.Driver.MongoCollectionImpl`1.CreateFindOperation[TProjection](FilterDefinition`1 filter, FindOptions`2 options)
         at MongoDB.Driver.MongoCollectionImpl`1.FindAsync[TProjection](IClientSessionHandle session, FilterDefinition`1 filter, FindOptions`2 options, CancellationToken cancellationToken)
         at MongoDB.Driver.MongoCollectionImpl`1.<>c__DisplayClass47_0`1.<FindAsync>b__0(IClientSessionHandle session)
         at MongoDB.Driver.MongoCollectionImpl`1.UsingImplicitSessionAsync[TResult](Func`2 funcAsync, CancellationToken cancellationToken)
         at MongoDB.Driver.IAsyncCursorSourceExtensions.ToListAsync[TDocument](IAsyncCursorSource`1 source, CancellationToken cancellationToken)
         at Catalog.API.Repositories.ProductRepository.GetProductsByCategory(String categoryName) in D:\dev\github\viniciusdesa\udemy-microsvcs-arch-n-impl\Udemy_MicroservicesArch\src\Catalog\Catalog.API\Repositories\ProductRepository.cs:line 51
         at Catalog.API.Controllers.CatalogController.GetProductByCategory(String category) in D:\dev\github\viniciusdesa\udemy-microsvcs-arch-n-impl\Udemy_MicroservicesArch\src\Catalog\Catalog.API\Controllers\CatalogController.cs:line 56
         at lambda_method29(Closure , Object )
         at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Logged|12_1(ControllerActionInvoker invoker)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
      --- End of stack trace from previous location ---
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)         at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
         at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
         at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
         at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
         at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

What could be wrong?
Follow a link to my code: https://github.com/viniciusdesa/udemy-microsvcs-arch-n-impl/tree/master/Udemy_MicroservicesArch/src/Catalog/Catalog.API

Best regards,

Vinicius

I put a bug in ProductRepository.GetProductsByCategory:

Wrong

        public async Task<IEnumerable<Product>> GetProductsByCategory(string categoryName)
        {
            FilterDefinition<Product> filter = Builders<Product>.Filter.ElemMatch(p => p.Category, categoryName);

            return await _context
                            .Products
                            .Find(filter)
                            .ToListAsync();
        }

Fixed

        public async Task<IEnumerable<Product>> GetProductsByCategory(string categoryName)
        {
            FilterDefinition<Product> filter = Builders<Product>.Filter.Eq(p => p.Category, categoryName);

            return await _context
                            .Products
                            .Find(filter)
                            .ToListAsync();
        }

Thanks @viniciusdesa for sharing this.
Also I had developed wrong one in first pace, but after that as you fixed, I had fixed with Eq method;

public async Task<IEnumerable<Product>> GetProductByCategory(string categoryName)