CodexBloom - Programming Q&A Platform

how to to retrieve data with Entity Framework Core after modifying a DbContext in ASP.NET Core 6

πŸ‘€ Views: 34 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-28
asp.net-core entity-framework-core csharp

Quick question that's been bugging me - I'm working on an ASP.NET Core 6 project where I'm using Entity Framework Core to interact with my database... I've recently made some changes to my `DbContext`, specifically by adding a new `DbSet` for a `Product` entity. However, after doing this, I'm working with an scenario where the data retrieval for my existing entities is not functioning as expected. The method responsible for fetching data is returning an empty list, and I'm not sure why this is happening. Here's a simplified version of my `DbContext` class: ```csharp public class ApplicationDbContext : DbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<Category> Categories { get; set; } public DbSet<Product> Products { get; set; } // Newly added DbSet } ``` And here’s the code I'm using to fetch the categories: ```csharp public async Task<List<Category>> GetCategoriesAsync() { return await _context.Categories.ToListAsync(); } ``` When I call `GetCategoriesAsync()`, I get an empty list. I have verified that there are existing records in the database. Additionally, I checked the connection string in my `appsettings.json`, and it appears to be correct: ```json "ConnectionStrings": { "DefaultConnection": "Server=myServer;Database=myDb;User Id=myUser;Password=myPass;" } ``` I also ensured that the migrations were applied correctly after adding the new `DbSet` by running `Update-Database`, and there were no errors reported during that process. I suspect that the scenario may be related to the way I'm configuring my `DbContext` in the `Startup.cs` file. Here's how I have it configured: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); } ``` I tried debugging the application and noticed that the `DbContext` is not throwing any exceptions, but still, the queried data is empty. Is there something I might have overlooked when modifying the `DbContext`, or could there be a caching scenario at play? Any insights would be greatly appreciated! The project is a application built with Csharp. Thanks for your help in advance! My development environment is CentOS. Is this even possible?