I’m encountering an issue with MongoDB Entity Framework Core where a shared nested object gets nullified when saving multiple entities. Here’s my scenario:
Models:
public class ExampleItem 
{
    public int Id { get; set; }
    public ExampleInternalItem InternalItem { get; set; }
}
public class ExampleInternalItem
{
    public string Name { get; set; }
}
DbContext Configuration:
public class ExampleCommonDbContext(DbContextOptions options) : DbContext(options)
{
    public DbSet<ExampleItem> ExampleItems { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ExampleItem>().ToCollection("example_collection");
    }
}
Repro Code:
var internalItem = new ExampleInternalItem { Name = "test" };
var item1 = new ExampleItem { Id = 1, InternalItem = internalItem };
var item2 = new ExampleItem { Id = 2, InternalItem = internalItem };
await context.ExampleItems.AddRangeAsync(item1, item2);
await context.SaveChangesAsync();
Expected Behavior:
Both documents should contain the complete InternalItem:
{
  "_id": 1,
  "InternalItem": {
    "Name": "test"
  }
},
{
  "_id": 2,
  "InternalItem": {
    "Name": "test"
  }
}
Actual Behavior:
The first document’s InternalItem becomes null:
{
  "_id": 1,
  "InternalItem": null
},
{
  "_id": 2,
  "InternalItem": {
    "Name": "test"
  }
}
Tested with:
MongoDB.EntityFrameworkCore 8.0.0
MongoDB.EntityFrameworkCore 9.0.0
- Is this a bug in the MongoDB EF Core provider?
- What’s the proper way to handle shared nested objects in MongoDB via EF Core?
- Should I be configuring the relationship differently in OnModelCreating?