简体   繁体   中英

System.ObjectDisposedException: Cannot access a disposed object. AplicationDbContext

I calling GetSurveysAuditorByUserEmail method. This method connects to remote another DB and return records.

public SurveysService(ApplicationDbContext context) {
  _context = context;
}

public IList<Survey> GetSurveysAuditorByUserEmail(string email) {
  var idsSurveys = new List<string>( );
  var surveys = new List<Survey>( );
  try {
    using(IDbConnection db = new SqlConnection(_connStringAudit)) {
      idsSurveys = db.Query<string>("Select (CONVERT(nvarchar(450), Id) + Funz) as IdRilievo From V_TemView Where Email = @email",
        new { email }).ToList( );

    }

    surveys = _context.Surveys.Where(o => idsSurveys.Contains(o.Id)).ToList( );
  }
  catch (Exception e) {
    _logger.Write(e.Message);
  }

  return surveys;
}

On the line surveys = _context.Surveys.Where(o => idsSurveys.Contains(o.Id)).ToList(); I get error:

System.ObjectDisposedException: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur is you are calling Dispose() on the context, or wrapping the context 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: 'ApplicationDbContext'.

EDIT :

I call this method in another class:

public async Task<List<IGrouping<int, Survey>>> GroupSurveyByIntervId(User user) {
  IList<Survey> surveys = new List<Survey>( );
  var statuses = _context.Statuses.ToList( );
  //var surv = _context.Surveys.ToList();

  var userRoles = await _userManager.GetRolesAsync(user);

  surveys = _surveysService.GetSurveysAuditorByUserEmail(user.Email);

  var groupSurv = surveys.GroupBy(x => x.InterventionId).ToList( );
  return groupSurv;
}

EDIT

I inject ApplicationDbContext in Startup.cs :

services.AddDbContext<ApplicationDbContext>(options =>
  options.UseSqlServer(
    Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<TrackingUser, TrackingRole>(options => {
    options.SignIn.RequireConfirmedEmail = false;
  })
  .AddEntityFrameworkStores<ApplicationDbContext>( );

How can I solve? Thank you

surveys = _context.Surveys.Where(o => idsSurveys.Contains(o.Id)).ToList();

You are trying to use that outside the using block. Do it like this

using (IDbConnection db = new SqlConnection(_connStringAudit))
{
    idsSurveys = db.Query<string>("Select (CONVERT(nvarchar(450), Id) + Funz) as IdRilievo From V_TemView Where Email = @email",
                      new { email }).ToList();
    surveys = _context.Surveys.Where(o => idsSurveys.Contains(o.Id)).ToList();
}

db is disposed outside this using block and so is the query object.

Few Clarifications: If you are using entity framework core, Do not using a separate dbconnection. If you want to connect to two different databases, then use different DataContext.

Do not open Parellal Connection to same DB. It is forcing the existing connection to close.

in case it is the same Database and you are using code first migration,

In DBContext class add DBSet<IdRilievo> property and access it from the same context object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM