Skip to content

Indexes not being automatically generated. #368

@wlewis22

Description

@wlewis22

Hi James (and any others who might be able to assist).

I've been using MongoFramework for sometime now on my current project and its brilliant. However I have run into a problem.

I am going to be honest, I am not sure if this is an issue or me doing something dumb.

I recently needed to add some text indexes to properties on an entity, in order to use the SearchText method. I tried adding the indexes using the Attribute decorator, as well as via the MongoDbContext in the OnConfiguringMapping method. Neither instance seemed to result in the indexes being created in my DB when the project was run.

I tried calling context.SaveChangesAsync() just in case that was required but to no avail. If I go to the DB and create the indexes manually, the SearchText method works fine. If I just allow MongoFramework to do its thing, it throws the below error.

MongoDB.Driver.MongoCommandException: Command aggregate failed: text index required for $text query.

Hopefully this is just me missing something in the doco and not an actual issue, as it seems pretty fundamental. Any assistance would be much appreciated.

Below is my DB Context, in case that helps.

public class DataContext : MongoDbContext
{
	public MongoDbSet<Creature> Creatures { get; set; }
	...other DbSets etc...

	public DataContext (IMongoDbConnection connection) : base (connection) 
	{
    }

	protected override void OnConfigureMapping (MappingBuilder mappingBuilder) {
        mappingBuilder.Entity<Creature>()
			.HasIndex(e => e.Name, b => b.HasType(IndexType.Text));

        mappingBuilder.Entity<Creature>()
            .HasIndex(e => e.Description, b => b.HasType(IndexType.Text));

        mappingBuilder.Entity<Creature>()
            .HasIndex(e => e.Source, b => b.HasType(IndexType.Text));
    }

	public override void SaveChanges () {
		OnBeforeSaving ();
		base.SaveChanges ();
	}

	public override async Task SaveChangesAsync (CancellationToken cancellationToken = default) {
		OnBeforeSaving ();
		await base.SaveChangesAsync (cancellationToken);
	}

	private void OnBeforeSaving () {
		ChangeTracker.DetectChanges ();

		foreach (var entity in ChangeTracker.Entries ()) {
			switch (entity.State) {
				case EntityEntryState.Added:
					if (entity.Entity is IEntityBase addedEntity) {
						addedEntity.CreatedOn = DateTime.UtcNow;
						addedEntity.ModifiedOn = DateTime.UtcNow;
					}
					break;

				case EntityEntryState.Updated:
					if (entity.Entity is IEntityBase modifiedEntity) {
						modifiedEntity.ModifiedOn = DateTime.UtcNow;
					}
					break;
			}
		}
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions