{"record":{"id":"b417330ac07209c4","repo":"microsoft/aspire","slug":"a-database-name-is-required-but-was-not-provided-specify-it","errorCode":null,"errorMessage":"A database name is required but was not provided. Specify it via the '{nameof(databaseName)}' parameter, the '{nameof(MongoDBEntityFrameworkCoreSettings.DatabaseName)}' setting, or include it in the connection string.","messagePattern":"A database name is required but was not provided\\. Specify it via the '(.+?)' parameter, the '(.+?)' setting, or include it in the connection string\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/Components/Aspire.MongoDB.EntityFrameworkCore/AspireMongoDBEntityFrameworkCoreExtensions.cs","lineNumber":86,"sourceCode":"            if (!string.IsNullOrEmpty(mongoUrl.DatabaseName))\n            {\n                settings.DatabaseName = mongoUrl.DatabaseName;\n            }\n        }\n\n        configureSettings?.Invoke(settings);\n\n        builder.Services.AddDbContextPool<TContext>(ConfigureDbContext);\n\n        ConfigureInstrumentation<TContext>(builder, settings);\n\n        void ConfigureDbContext(DbContextOptionsBuilder dbContextOptionsBuilder)\n        {\n            ConnectionStringValidation.ValidateConnectionString(settings.ConnectionString, connectionName, DefaultConfigSectionName, $\"{DefaultConfigSectionName}:{typeof(TContext).Name}\", isEfDesignTime: EF.IsDesignTime);\n\n            if (string.IsNullOrEmpty(settings.DatabaseName))\n            {\n                throw new InvalidOperationException($\"A database name is required but was not provided. Specify it via the '{nameof(databaseName)}' parameter, the '{nameof(MongoDBEntityFrameworkCoreSettings.DatabaseName)}' setting, or include it in the connection string.\");\n            }\n\n            dbContextOptionsBuilder.UseMongoDB(settings.ConnectionString!, settings.DatabaseName);\n\n            configureDbContextOptions?.Invoke(dbContextOptionsBuilder);\n        }\n    }\n\n    /// <summary>\n    /// Configures logging and telemetry for the <see cref=\"DbContext\" />.\n    /// </summary>\n    /// <typeparam name=\"TContext\">The <see cref=\"DbContext\" /> that needs to be configured.</typeparam>\n    /// <param name=\"builder\">The <see cref=\"IHostApplicationBuilder\" /> to read config from and add services to.</param>\n    /// <param name=\"configureSettings\">An optional delegate that can be used for customizing options. It's invoked after the settings are read from the configuration.</param>\n    /// <remarks>Reads the configuration from \"Aspire:MongoDB:EntityFrameworkCore:{typeof(TContext).Name}\" config section, or \"Aspire:MongoDB:EntityFrameworkCore\" if former does not exist.</remarks>\n    /// <exception cref=\"ArgumentNullException\">Thrown if mandatory <paramref name=\"builder\"/> is null.</exception>\n    /// <exception cref=\"InvalidOperationException\">Thrown when mandatory <see cref=\"DbContext\"/> is not registered in DI.</exception>\n    public static void EnrichMongoDbContext<[DynamicallyAccessedMembers(RequiredByEF)] TContext>(","sourceCodeStart":68,"sourceCodeEnd":104,"githubUrl":"https://github.com/microsoft/aspire/blob/25830f84bd145686607ad00c057b3f84e2e51d43/src/Components/Aspire.MongoDB.EntityFrameworkCore/AspireMongoDBEntityFrameworkCoreExtensions.cs#L68-L104","documentation":"MongoDB requires a database name for UseMongoDB(connectionString, databaseName). The AddMongoDbContext ConfigureDbContext callback validates the connection string first, then throws if settings.DatabaseName is still null/empty — meaning the databaseName parameter, the MongoDBEntityFrameworkCoreSettings.DatabaseName setting, and the 'Database=' part of the connection string were all absent.","triggerScenarios":"Calling AddMongoDbContext<TContext>(connectionName) without a databaseName argument where the connection string has no database part and the settings section lacks DatabaseName; validation happens lazily when the DbContext options are configured.","commonSituations":"Connection string copied from Atlas (e.g. mongodb+srv://user:pass@cluster/) without /dbname; refactor from the named overload to the inferred overload; DatabaseName key typo'd in the 'Aspire:MongoDB:EntityFrameworkCore' section; EF design-time factory generating options with a bare connection string.","solutions":["Use the AddMongoDbContext overload that takes a databaseName parameter.","Or append the database to the connection string: mongodb+srv://.../mydb.","Or set DatabaseName in the 'Aspire:MongoDB:EntityFrameworkCore' configuration section (or the :<TContext.Name> override).","Ensure the EF design-time factory also supplies a database name when running 'dotnet ef' commands."],"exampleFix":"// before\nbuilder.AddMongoDbContext<CatalogContext>(\"mongo\"); // connection string has no /db\n// after\nbuilder.AddMongoDbContext<CatalogContext>(\"mongo\", \"catalog\");\n// or: \"ConnectionStrings\": { \"mongo\": \"mongodb+srv://user:pass@cluster/catalog\" }","handlingStrategy":"validation","validationCode":"// before AddMongoDbContext without a databaseName parameter\nvar cs = builder.Configuration.GetConnectionString(connectionName) ?? \"\";\nvar dbNameFromCs = cs.Split('/').LastOrDefault(p => p.Contains('?') ? p.Split('?')[0].Length > 0 : p.Length > 0);\nvar settingDb = builder.Configuration[\"Aspire:MongoDB:EntityFrameworkCore:DatabaseName\"];\nif (string.IsNullOrEmpty(dbNameFromCs) && string.IsNullOrEmpty(settingDb))\n{\n    throw new InvalidOperationException(\"MongoDB database name must come from the parameter, settings, or connection string.\");\n}","typeGuard":"bool HasMongoDatabaseName(string? param, string? settingDb, string? cs) => !string.IsNullOrEmpty(param) || !string.IsNullOrEmpty(settingDb) || (cs?.Split('/').LastOrDefault()?.Split('?')[0].Length > 0);","tryCatchPattern":"try { builder.AddMongoDbContext<CatalogContext>(\"mongo\"); }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"A database name is required\")) { builder.AddMongoDbContext<CatalogContext>(\"mongo\", \"catalog\"); }","preventionTips":["Pass the databaseName parameter explicitly instead of relying on connection-string inference.","When copying Atlas connection strings, remember to append /databasename before any '?'.","If you use EF design-time factories, give them a database name too or 'dotnet ef' will fail."],"tags":["mongodb","ef-core","missing-database-name","configuration"],"backgroundTag":"missing-required-argument","analyzedSha":"25830f84bd145686607ad00c057b3f84e2e51d43","analyzedAt":"2026-09-16T11:10:06.193Z","contentChangedAt":"2026-09-16T11:10:06.193Z","schemaVersion":2},"datasetVersion":"2026-09-21T09:17:21.228Z"}