'.Net core/EF : cannot access a disposed object. A common cause of this error is disposing a context

I am using Net core, and am facing this famous problem i have this sample :

var model = await context.MethAppointementsPreventifs
            .FirstOrDefaultAsync(item => item.StartDate >= DateTodelete 
            && item.IdOperation == XpertHelper.IdOperation);
if (model != null)
{
 var OpInfos = await context.MethOperations.AsNoTracking()
               .FirstOrDefaultAsync(item => item.Idoperation == model.IdOperation);
 context.MethAppointementsPreventifs.Remove(model);
 await context.SaveChangesAsync();
}

when i get my "model" and "OpInfos" no context disposed or excpetion thrown but in the line of :

context.MethAppointementsPreventifs.Remove(model);

it throws that exception, my methode doesnt return an async void :

public static async Task<int> ClearAppPreventif(KBFsteelContext context)
{
    //clear from the day of intervention 
    var DateTodelete = XpertHelper.DateIntervention;
    bool IsStill = true;
    while (IsStill)
    {
        var model = await context.MethAppointementsPreventifs
            .FirstOrDefaultAsync(item => item.StartDate >= DateTodelete && item.IdOperation == XpertHelper.IdOperation);
        if (model != null)
        {
            var OpInfos = await context.MethOperations.AsNoTracking().FirstOrDefaultAsync(item => item.Idoperation == model.IdOperation);
            context.MethAppointementsPreventifs.Remove(model);
            await context.SaveChangesAsync();
            if (OpInfos.Unité == 1)
            {
                var newDayDate = DateTodelete.AddDays(OpInfos.Fréquence);
                DateTodelete = newDayDate;
            }//jours
            if (OpInfos.Unité == 2)
            {
                var newDayDate = DateTodelete.AddMonths(OpInfos.Fréquence);
                DateTodelete = newDayDate;
            }//Mois
            if (OpInfos.Unité == 3)
            {
                var newDayDate = DateTodelete.AddYears(OpInfos.Fréquence);
                DateTodelete = newDayDate;
            }//Annees
        }
        else
        {
            IsStill = false;
        }
    }
    return 1;
}

and am calling it with await... so what should i do ?



Solution 1:[1]

Maybe your OpInfos is getting destroyed. Especially if you have a cascade delete behavior. Why you don't change your code to this:

....your code

if (model != null)
{
var operationId=model.IdOperation:
 context.MethAppointementsPreventifs.Remove(model);
var result = await context.SaveChangesAsync();
if (result==0) return 0; //error

var OpInfos = await context.MethOperations.AsNoTracking().FirstOrDefaultAsync(item => item.Idoperation ==operatonId);
if(OpInfos ==null) return 0; //error

 if (OpInfos.Unité == 1)
....continue your code

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1