I am trying to query a MongoDB collection using EF Core. When a string-type field is missing (i.e. Password), it’s returned as null
(as expected), but when a complex type field is missing (the Group field in this case) in ANY document within the collection, I get the below error:
Microsoft.EntityFrameworkCore.Query: Error: An exception occurred while iterating over the results of a query for context type 'MongoStore.MongoContext'.
System.Collections.Generic.KeyNotFoundException: Element 'Group' not found.
at MongoDB.Bson.BsonDocument.get_Item(String name)
at lambda_method8(Closure, QueryContext, BsonDocument)
at MongoDB.EntityFrameworkCore.Query.QueryingEnumerable`2.Enumerator.MoveNextHelper()
at MongoDB.EntityFrameworkCore.Query.QueryingEnumerable`2.Enumerator.MoveNext()
Here’s how I’m trying to query the database:
app.MapGet(
"/users",
(MongoContext context) =>
{
var users = context.Users.FirstOrDefault();
return users;
}
);
Model class:
[Collection("Users")]
public class User
{
public ObjectId Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
public Group? Group { get; set; }
}
public class Group
{
public string Name { get; set; } = string.Empty;
}
Context class:
public class MongoContext : DbContext
{
public DbSet<User> Users { get; init; }
public MongoContext(DbContextOptions<MongoContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<User>();
}
}