I’ve changed my use of DbContext to incorporating DbContextFactory in order to handle multiple sql transactions. I’ve run into a couple questions/errors trying to do this.
I have 3 different tables in my database that are accessed for different functions so I created 3 different services to handle them. Is this correct? Is there a better way? I'm not sure this if this is related to the problem but I want to make sure I'm not adding unnecessary complications.
My tables: Category, Expense, Items My services: CategoryService, ExpenseService, ItemService Each service has a GetAll, GetbyKey, Update, and Delete.
After adding the DbContextFactory to my services, I’m getting an error I don’t understand. Here’s part of my Program.cs code:
builder.Services.AddRazorPages(); builder.Services.AddServerSideBlazor(); builder.Services.AddDbContextFactory<BudgetDBContext>(options => options.UseSqlServer("DefaultConnection")); builder.Services.AddScoped<ExpenseService>(); builder.Services.AddScoped<CategoryService>(); builder.Services.AddScoped<ItemService>(); builder.Services.AddDbContext<BudgetDBContext>(item => item.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); var app = builder.Build();
Here’s the part of my page code:
private async void GetCategories()
{
categories = await categoryService.GetAllCategories();
GetUICategories(categories, uiCategories, uiSubCategories);
}
Here’s the part of my CategoryService code:
public async Task<List<Category>> GetAllCategories()
{
using var dbContext = _factory.CreateDbContext();
return await dbContext.Categories.ToListAsync();
}
Here’s the error that’s happening at return await dbContext.Categories.ToListAsync(); in the CategoryService:
System.InvalidOperationException: 'Instance failure.'
I think I must have added the DbContextFactory incorrectly in the Progam file but I'm not sure that's what the problem is.
Update: I meant to post the following for the AddDbContextFactory line.
builder.Services.AddDbContextFactory<BudgetDBContext>(options => options.UseSqlServer(@"Server=DESKTOP-JMIKVDI\\SQLEXPRESS;Database=BudgetDB;Trusted_Connection=True;TrustServerCertificate=True"));
Using DefaultConnection as AddDbContext does changes the error.
builder.Services.AddDbContextFactory<BudgetDBContext>(options => options.UseSqlServer("DefaultConnection"));