Search code examples
entity-frameworkentity-framework-6datacontext

How to "clear" data context


Some my script updates local data from external resources, get part of data, update and then get next part of data... my update code is:

    public void UpdateDrivers(List<Domain.POCO.Vistracks.VistrackDriverInfoDomain> list)
    {
        foreach (var model in list)
        {
            var driver = (from i in _db.Drivers
                          where i.AspNetUser.UserName.Equals(model.Email, StringComparison.InvariantCultureIgnoreCase)
                          select i).FirstOrDefault();

            driver = mapper.Map<VistrackDriverInfoDomain, Infrastructure.Asset.Driver>(model, driver);
            driver.IsVistracksAdded = true;
            driver.VistracksDateSync = DateTime.Now;
        }
        _db.SaveChanges();
    }

ok, it works if data is valid. Sometimes data can be invalid and it throws exception. I need to pass this part of data and try with the next. But when I try with the next part of data (valid data) it throws the same exception again. I try to clear unchanged records by the following way:

_db.ChangeTracker.Entries().Where(x => x.State != EntityState.Unchanged).ToList().Clear();

but it does not help. How to do it?


Solution

  • I made it the following way:

    var changes = _db.ChangeTracker.Entries().Where(x => x.State != EntityState.Unchanged).ToList();
    foreach (var entity in changes)
    {
         _db.Entry(entity.Entity).State = EntityState.Detached;
    }