Working with a project in c#, ASP.NET Core with Authentication, MongoDB.Driver and MongoDB.EntityframeworkCore. I'm trying to store a userID as a string in a shopping cart and find the shopping cart using that data. I manage to add items to the cart and when I go to the cart page and call a get-method, it manages to find the cart with no problems. Problem is that if I restart the application, log in with user and go to the cart page again I get the Bson desiralization error:
BsonSerializationException: Unknown discriminator value 'List`1'.
It's when I'm calling the FirstOrDefaultAsync method when I get the deserialization error after I restart the application.
The GetItems code:
public async Task<CartDto> GetItems()
{
var user = signInManager.Context.User.Identity;
if (user is not null && user.IsAuthenticated)
{
var identity = System.Security.Claims.ClaimTypes.NameIdentifier;
var userId = signInManager.Context.User.FindFirst(identity)?.Value;
var userCart = await context.Cart.FirstOrDefaultAsync(c => c.UserId == userId);
if (userCart is not null)
{
CartDto cartDto = new()
{
Id = userCart.Id.ToString(),
UserId = userCart.UserId,
Products = userCart.Products
};
return cartDto;
}
}
}
The Cart class, which is stored in MongoDB:
[Collection("Cart")]
public class Cart
{
public ObjectId Id { get; set; }
public required string UserId { get; set; }
public List<string> Products { get; set; }
}
As of version 7.0.0-preview.1, the MongoDB Entity Framework Provider seems to serialize List<T>
incorrectly so that the list items are serialized in the following form, instead of serializing plain strings:
{
// ...
"Products": {
"_t": "List`1",
"_v": [
"Test1",
"Test2"
]
}
}
Upon deserialization, the provider expects plain string values in the array, but encounters the _t
type discriminator so that an error is raised.
This Jira ticket describes a related issue.