1

Error Discription

System.ObjectDisposedException: Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling 'Dispose' on the context instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances. Object name: 'MyDbContext'.

My Model Class

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace SAPConnection.Data
{
    public class LeaveModel
    {
        [Key]
        public int Id { get; set; }
        public String Reason { get; set; } = "";
        public DateTime RequestDate { get; set; } = DateTime.Now;
        public DateTime ToDate { get; set; } = DateTime.Now;

        public DateTime FromDate { get; set; } = DateTime.Now;
        public LeaveTypeModel LeaveType { get; set; }
        [NotMapped]
        public byte[] Attachment { get; set; }


    }
}

public enum LeaveTypeModel
{
    Casual, Sick, Annual
}

My LeaveService Class

using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace SAPConnection.Data
{
    public class LeaveService
    {
        private readonly MyDbContext _context;

        public LeaveService(MyDbContext context)
        {
            _context = context;
        }

        public async Task<List<LeaveModel>> GetLeavesAsync()
        {
            return await _context.leaveModel.ToListAsync();
        }

        public async Task<LeaveModel> GetLeaveAsync(int id)
        {
            return await _context.leaveModel.FindAsync(id);
        }

        public async Task CreateLeaveAsync(LeaveModel leave)
        {
            _context.leaveModel.Add(leave);
            await _context.SaveChangesAsync();
        }

        public async Task UpdateLeaveAsync(LeaveModel leave)
        {
            _context.Entry(leave).State = EntityState.Modified;
            await _context.SaveChangesAsync();
        }

        public async Task DeleteLeaveAsync(int id)
        {
            var leave = await _context.leaveModel.FindAsync(id);
            _context.leaveModel.Remove(leave);
            await _context.SaveChangesAsync();
        }
    }
}

My Function which submit leaves

private async Task submitLeaves()
    {


        await leaveService.CreateLeaveAsync(newLeave);
        NavigationManager.NavigateTo("/");


    }

My Program.cs Class

using Blazored.Toast;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using SAPConnection.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using SAPConnection.Areas.Identity.Data;
using System.Configuration;

var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("SAPConnectionContextConnection") ?? throw new InvalidOperationException("Connection string 'SAPConnectionContextConnection' not found.");

builder.Services.AddDbContext<SAPConnectionContext>(options => options.UseSqlServer(connectionString));
builder.Services.AddDbContext<MyDbContext>(options => options.UseSqlServer(connectionString));
builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true).AddEntityFrameworkStores<SAPConnectionContext>();
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();
builder.Services.AddScoped<LeaveService>();

builder.Services.AddBlazoredToast();
var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();
abraKajapa
  • 19
  • 3
  • And what calls `submitLeaves`? – Stephen Cleary Feb 24 '23 at 12:34
  • @StephenCleary This HTML input which is inside form. `` – abraKajapa Feb 24 '23 at 12:38
  • 2
    While I'm not sure where your specific problem is (I can't see it in the code you've provided), you should switch to using a DbContextFactory. There's an MS Docs article here - https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/#using-a-dbcontext-factory-eg-for-blazor and an SO answer on the subject here - https://stackoverflow.com/questions/67374706/blazor-server-mixing-ef-core-dbcontextfactory-with-dbcontext. Both explain why you should switch. – MrC aka Shaun Curtis Feb 24 '23 at 12:46
  • `AddScoped()` looks like a good idea but in Blazor Server you don't have suitable Scopes. So yes, use a DbContextFactory. – H H Feb 24 '23 at 12:58

1 Answers1

0

I changed my Code to following and it fixed the issues.

//DBContext class

using Microsoft.EntityFrameworkCore;

namespace SAPConnection.Data
{
    public class MyDbContext : DbContext
    {
        public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
        {
        }

        public DbSet<LeaveModel> leaveModel { get; set; }
    }
}

//DBCOntextFacoty

using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore;
using System.Configuration;

namespace SAPConnection.Data
{
    public class LeaveDbContextFactory : IDesignTimeDbContextFactory<MyDbContext>
    {
        public MyDbContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
            optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=SAPConnection;Trusted_Connection=True;MultipleActiveResultSets=true");

            return new MyDbContext(optionsBuilder.Options);
        }
    }
}

//LeaveService

using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace SAPConnection.Data
{
    public class LeaveService
    {
        private readonly IDbContextFactory<MyDbContext> _contextFactory;

        public LeaveService(IDbContextFactory<MyDbContext> contextFactory)
        {
            _contextFactory = contextFactory;
        }

        public async Task<List<LeaveModel>> GetLeavesAsync()
        {
            using var context = _contextFactory.CreateDbContext();
            return await context.leaveModel.ToListAsync();
        }

        public async Task<LeaveModel> GetLeaveAsync(int id)
        {
            using var context = _contextFactory.CreateDbContext();
            return await context.leaveModel.FindAsync(id);
        }

        public async Task CreateLeaveAsync(LeaveModel leave)
        {
            using var context = _contextFactory.CreateDbContext();
            context.leaveModel.Add(leave);
            await context.SaveChangesAsync();
        }

        public async Task UpdateLeaveAsync(LeaveModel leave)
        {
            using var context = _contextFactory.CreateDbContext();
            context.Entry(leave).State = EntityState.Modified;
            await context.SaveChangesAsync();
        }

        public async Task DeleteLeaveAsync(int id)
        {
            using var context = _contextFactory.CreateDbContext();
            var leave = await context.leaveModel.FindAsync(id);
            context.leaveModel.Remove(leave);
            await context.SaveChangesAsync();
        }
    }
}

//program.cs

using Blazored.Toast;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using SAPConnection.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using SAPConnection.Areas.Identity.Data;
using System.Configuration;

var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("SAPConnectionContextConnection") ?? throw new InvalidOperationException("Connection string 'SAPConnectionContextConnection' not found.");

builder.Services.AddDbContext<SAPConnectionContext>(options => options.UseSqlServer(connectionString));

builder.Services.AddDbContextFactory<MyDbContext>(options => options.UseSqlServer(connectionString));

builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true).AddEntityFrameworkStores<SAPConnectionContext>();
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();
builder.Services.AddScoped<LeaveService>();

builder.Services.AddBlazoredToast();
var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();
abraKajapa
  • 19
  • 3
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 01 '23 at 00:30