[EF-67] KeyNotFoundException does not include key name in SerializationHelper.ReadElementValue Created: 01/Nov/23  Updated: 14/Nov/23  Resolved: 14/Nov/23

Status: Closed
Project: Entity Framework
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Unknown
Reporter: James Kovacs Assignee: Oleksandr Poliakov
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

When you read a document from the database and the C# property names don't match the BSON element names, a KeyNotFoundException is thrown on line 165 of SerializationHelper.cs for non-nullable types. Unfortunately we don't include the name of the missing key in the error, which makes it difficult to debug the problem.

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Conventions;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.EntityFrameworkCore.Extensions;
using MongoDB.EntityFrameworkCore.Metadata.Conventions;
 
var client = new MongoClient("mongodb://localhost:27017");
 
using var db = CustomerDbContext.Create(client.GetDatabase("test"));
 
var sally = db.Customers.First(x => x.FirstName == "Sally");
Console.WriteLine(sally);
 
class Customer
{
    public ObjectId Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int FavouriteNumber { get; set; }
    public override string ToString() => $"{FirstName} {LastName} ({Id}) - {FavouriteNumber}";
}
 
class CustomerDbContext : DbContext
{
    public DbSet<Customer> Customers { get; init; }
 
    public static CustomerDbContext Create(IMongoDatabase database)
    {
        return new CustomerDbContext(new DbContextOptionsBuilder<CustomerDbContext>()
            .UseMongoDB(database.Client, database.DatabaseNamespace.DatabaseName)
            .Options);
    }
 
    public CustomerDbContext(DbContextOptions options) : base(options)
    {
    }
 
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
 
        var customerModelBuilder = modelBuilder.Entity<Customer>();
        customerModelBuilder.ToCollection("customers");
    }
}

Insert the following document into the database:

use test
db.customers.insertOne({
    FirstName: 'Sally',
    LastName: 'Smith',
    favourite_number: 42
  })

We should include the key name that we cannot find in the error message.


Generated at Thu Feb 08 08:26:49 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.