MongoDB EF Core: Nested object becomes null when saving multiple entities referencing the same instance

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

  1. Is this a bug in the MongoDB EF Core provider?
  2. What’s the proper way to handle shared nested objects in MongoDB via EF Core?
  3. Should I be configuring the relationship differently in OnModelCreating?

Hi.
These types of nested obejcts in EF are known as “owned entities”. Each instance may only have a single owner.
This is a limitation of EF itself not the MongoDB provider.
You would need to create separate instances of each child object.