Troubleshooting tips for indices not getting created when using `HasIndex` in EF Core 9.0?

The MongoDB integration into EF Core 9.0 says it supports (and provides examples for) using the HasIndex() method of the Entity Builder to create indices. However, I can’t seem to get it to work.

This is my model setup code:

        builder.Entity<GameDBObject>(bldr =>
        {
            bldr.HasIndex(dbobj => dbobj.Name).IsUnique(true);
            bldr.HasIndex("Name").IsUnique(true);
            // no index is created with either of the above two statements
            bldr.HasKey(dbobj => dbobj.Id);
            bldr.Property(dbobj => dbobj.Id)
                .HasConversion(id => ObjectId.Parse(id), oid => oid.ToString())
                .HasValueGenerator<StringObjectIdValueGenerator>();
        });

I’ve tried both of the first two statements in the Entity Builder (giving the name of the property or a reference to it); neither results in an index being created.

How do I go about troubleshooting this?

In the debug logs, the only references I see to indexes are about the Id field in a contained GamePlayer object (which I tried changing to PlayerRef and it still complains about the Id field).

Hello, just to make sure are you calling dbContext.Database.EnsureCreated() method?


side note: You cannot modify/delete indexes with the provider after they are created btw.

1 Like

Hi Johnson.

As Daniel said, you’ll need to make sure you have db.Database.EnsureCreated() somewhere in your app start-up.

That goes ahead and checks the index names exist and if not creates them. Bear in mind if you change the index definition you’ll need to write code to drop the old index name first as there is no migration system for non-relational EF providers.

1 Like

Thank you both; I finally got a chance to test today and that was what was missing.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.