C
C#2mo ago
habtard

EF core can't use any tooling

Running dotnet ef migrations script --project=App.Database Rusults in
Unable to create a 'DbContext' of type ''. The exception 'Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions' while attempting to activate 'App.Database.AppContext'
Unable to create a 'DbContext' of type ''. The exception 'Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions' while attempting to activate 'App.Database.AppContext'
21 Replies
habtard
habtard2mo ago
GitHub
Migrations add doesn't work with Microsoft.Extensions.Hosting · Iss...
Hi Folks, I am building a WinUI 3 app and want to use SQLite using ef core. When using the Microsoft.Extensions.Hosting package, the dotnet ef migrations add command doesn't give any errors but...
Salman
Salman2mo ago
Check your DB context and especially connection string. There's something wrong with connection string either it's not accessible or not correct. Or something wrong with your Db Context class.
habtard
habtard2mo ago
Hmm well the connection string works on normal run, what should I check with context? Thanks for the help BTW
hime
hime2mo ago
Show your code
Salman
Salman2mo ago
you can show your code i.e db context
habtard
habtard2mo ago
public class SadieContext(DbContextOptions options) : DbContext(options)
{
public DbSet<NavigatorCategory> NavigatorCategories { get; set; }
public DbSet<NavigatorTab> NavigatorTabs { get; set; }
public DbSet<FurnitureItem> FurnitureItems { get; set; }
public DbSet<CatalogItem> CatalogItems { get; set; }
public DbSet<CatalogPage> CatalogPages { get; set; }
public DbSet<CatalogFrontPageItem> CatalogFrontPageItems { get; set; }
public DbSet<RoomCategory> RoomCategories { get; set; }
public DbSet<RoomChatMessage> RoomChatMessages { get; set; }
public DbSet<RoomFurnitureItem> RoomFurnitureItems { get; set; }
public DbSet<RoomPlayerRight> RoomPlayerRights { get; set; }
public DbSet<RoomSettings> RoomSettings { get; set; }
public DbSet<RoomLayout> RoomLayouts { get; set; }
public DbSet<Room> Rooms { get; set; }
public DbSet<Player> Players { get; set; }
public DbSet<PlayerData> PlayerData { get; set; }
public DbSet<PlayerFurnitureItem> PlayerFurnitureItems { get; set; }
public DbSet<PlayerBadge> PlayerBadges { get; set; }
public DbSet<Badge> Badges { get; set; }
public DbSet<CatalogClubOffer> CatalogClubOffers { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// truncated for shortness
}
}
public class SadieContext(DbContextOptions options) : DbContext(options)
{
public DbSet<NavigatorCategory> NavigatorCategories { get; set; }
public DbSet<NavigatorTab> NavigatorTabs { get; set; }
public DbSet<FurnitureItem> FurnitureItems { get; set; }
public DbSet<CatalogItem> CatalogItems { get; set; }
public DbSet<CatalogPage> CatalogPages { get; set; }
public DbSet<CatalogFrontPageItem> CatalogFrontPageItems { get; set; }
public DbSet<RoomCategory> RoomCategories { get; set; }
public DbSet<RoomChatMessage> RoomChatMessages { get; set; }
public DbSet<RoomFurnitureItem> RoomFurnitureItems { get; set; }
public DbSet<RoomPlayerRight> RoomPlayerRights { get; set; }
public DbSet<RoomSettings> RoomSettings { get; set; }
public DbSet<RoomLayout> RoomLayouts { get; set; }
public DbSet<Room> Rooms { get; set; }
public DbSet<Player> Players { get; set; }
public DbSet<PlayerData> PlayerData { get; set; }
public DbSet<PlayerFurnitureItem> PlayerFurnitureItems { get; set; }
public DbSet<PlayerBadge> PlayerBadges { get; set; }
public DbSet<Badge> Badges { get; set; }
public DbSet<CatalogClubOffer> CatalogClubOffers { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// truncated for shortness
}
}
Just the context? truncated OnModelCreating its just full of relationship mappings
Salman
Salman2mo ago
You need to change the method like this:
public class SadieContext(DbContextOptions<SadieContext> options) : DbContext(options)
public class SadieContext(DbContextOptions<SadieContext> options) : DbContext(options)
then try
habtard
habtard2mo ago
I still get Unable to create a 'DbContext' of type ''. The exception 'Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[Sadie.Database.SadieContext]' I think the issue is my entities are in a seperate assembly to where the DbContext gets registered in the ioc?
hime
hime2mo ago
Can you show how you register your dbconfext to the service collection Did you use .AddDbContext
habtard
habtard2mo ago
@hime my code is in that Reddit post Sorry but I am on mobile and I can’t copy it right now
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
Salman
Salman2mo ago
yeah and everybody doesn't have reddit account as well
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
Salman
Salman2mo ago
Something can be wrong in Program.cs as well where you're registering your context. I got this error when I wasn't getting the connection string in the Program.cs . idk why they're not letting me in xD. I've account but seems like they've blocked for some reason
habtard
habtard2mo ago
Hey the program.cs is on reddit too I'll attach it here now 🙂 Program.cs:
var host = Host.CreateDefaultBuilder()
.ConfigureServices((context, collection) => ServerServiceCollection.AddServices(collection, context.Configuration))
.UseSerilog((hostContext, _, logger) =>
logger.ReadFrom.Configuration(hostContext.Configuration)
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning))
.Build();
var host = Host.CreateDefaultBuilder()
.ConfigureServices((context, collection) => ServerServiceCollection.AddServices(collection, context.Configuration))
.UseSerilog((hostContext, _, logger) =>
logger.ReadFrom.Configuration(hostContext.Configuration)
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning))
.Build();
ServerServiceCollection
public static class ServerServiceCollection
{
public static void AddServices(IServiceCollection serviceCollection, IConfiguration config)
{
DatabaseServiceCollection.AddServices(serviceCollection, config);
MapperServiceCollection.AddServices(serviceCollection, config);
// ...
}
}
public static class ServerServiceCollection
{
public static void AddServices(IServiceCollection serviceCollection, IConfiguration config)
{
DatabaseServiceCollection.AddServices(serviceCollection, config);
MapperServiceCollection.AddServices(serviceCollection, config);
// ...
}
}
In DatavaseServiceCollection:
serviceCollection.AddDbContext<SadieContext>(options =>
{
options.UseMySql(connectionString, MySqlServerVersion.LatestSupportedServerVersion, mySqlOptions =>
mySqlOptions.EnableRetryOnFailure(
maxRetryCount: 10,
maxRetryDelay: TimeSpan.FromSeconds(30),
errorNumbersToAdd: null
))
.UseSnakeCaseNamingConvention();
});
serviceCollection.AddDbContext<SadieContext>(options =>
{
options.UseMySql(connectionString, MySqlServerVersion.LatestSupportedServerVersion, mySqlOptions =>
mySqlOptions.EnableRetryOnFailure(
maxRetryCount: 10,
maxRetryDelay: TimeSpan.FromSeconds(30),
errorNumbersToAdd: null
))
.UseSnakeCaseNamingConvention();
});
Salman
Salman2mo ago
seems okay. Are the other db commands working correctly or none of them are working ? Like adding migrations, updating the db etc. If none of the ef tools command are working then you can log the connection string to the console and check if it's being passed correctly if you haven't already checked that.
habtard
habtard2mo ago
well... I check that in the app
var connectionString = config.GetConnectionString("Default");

if (string.IsNullOrEmpty(connectionString))
{
throw new Exception("Default connection string is missing");
}
var connectionString = config.GetConnectionString("Default");

if (string.IsNullOrEmpty(connectionString))
{
throw new Exception("Default connection string is missing");
}
I'll dump it to be sure, also pretty sure its every tool It does dump it but with warnings this time
The Entity Framework tools version '8.0.3' is older than that of the runtime '8.0.4'. Update the tools for the latest features and bug fixes. See https://aka.ms/AAc1fbw for more information.
The Entity Framework tools version '8.0.3' is older than that of the runtime '8.0.4'. Update the tools for the latest features and bug fixes. See https://aka.ms/AAc1fbw for more information.
An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider.
An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider.
Adding a IDesignTimeDbContextFactory has fixed it
Salman
Salman2mo ago
use IsNullOrWhitespace , like what if string is not null but only contains whitespaces
habtard
habtard2mo ago
@Salman good point All migrations do is make one table, I don't think its finding my models correctly.
CREATE TABLE IF NOT EXISTS `__EFMigrationsHistory` (
`migration_id` varchar(150) CHARACTER SET utf8mb4 NOT NULL,
`product_version` varchar(32) CHARACTER SET utf8mb4 NOT NULL,
CONSTRAINT `pk___ef_migrations_history` PRIMARY KEY (`migration_id`)
) CHARACTER SET=utf8mb4;
CREATE TABLE IF NOT EXISTS `__EFMigrationsHistory` (
`migration_id` varchar(150) CHARACTER SET utf8mb4 NOT NULL,
`product_version` varchar(32) CHARACTER SET utf8mb4 NOT NULL,
CONSTRAINT `pk___ef_migrations_history` PRIMARY KEY (`migration_id`)
) CHARACTER SET=utf8mb4;
Salman
Salman2mo ago
Well another thing you can do is to try update/reinstall the packages make sure efcore is up to date, apparently the code looks good and don't have any problems as far as I see.