Search code examples
c#entity-frameworkentity-framework-6ef-code-firstcode-first

EF : why child records are not deleted


I have the following structure:

public partial class Driver 
{
    public int ID { get; set; }
    //....

    #region Vistracks Required Fields

    public virtual ProblemSyncToVistracksDriver ProblemSyncToVistracksDriver { get; set; }

    #endregion
}


public partial class ProblemSyncToVistracksDriver
{
    [Key, ForeignKey("Driver")]
    public int DriverId { get; set; }
    public virtual Driver Driver { get; set; }

    public int? ResponseCode { get; set; }
    public string Message { get; set; }
    public string Description { get; set; }
    public bool IsServerError { get; set; }
    public DateTime DateAdded { get; set; }
}


modelBuilder.Entity<ProblemSyncToVistracksDriver>()
    .HasRequired(s => s.Driver)
    .WithOptional(ad => ad.ProblemSyncToVistracksDriver)
    .WillCascadeOnDelete(false);

then I try to remove a record from ProblemSyncToVistracksDriver for concrete driver:

        var driver = await (from i in _db.Drivers where i.AspNetUser.UserName.Equals(model.Email, StringComparison.InvariantCultureIgnoreCase) select i).FirstOrDefaultAsync();
        if (driver == null)
            throw new NullReferenceException();

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

        _db.Entry(driver).State = EntityState.Modified;
        await _db.SaveChangesAsync();

no errors, all other changes are saved. But record in ProblemSyncToVistracksDriver is not deleted. Why and how to fix it?


Solution

  • In order to remove a child record you need first to get it from database and then you can set it to null:

    var driver=_db.Drivers.Include(x=>x.ProblemSyncToVistracksDrivers)
    .FirstOrDefaultAsync(x=>x.AspNetUser.UserName.Equals(model.Email, StringComparison.InvariantCultureIgnoreCase));
    driver.ProblemSyncToVistracksDriver = null;
     await _db.SaveChangesAsync();
    

    more explanations you can find here similar question