EF:为什么不删除子记录

EF : why child records are not deleted

我有以下结构:

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);

然后我尝试从 ProblemSyncToVistracksDriver 中删除具体驱动程序的记录:

        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();

没有错误,所有其他更改已保存。但是 ProblemSyncToVistracksDriver 中的记录并没有被删除。为什么以及如何修复它?

要删除子记录,您需要先从数据库中获取它,然后将其设置为空:

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

您可以在此处找到更多解释

在您的模型中,您指定:

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

此规范表明每个 ProblemSyncToVistrackDriver 对象恰好属于一个 Driver,不是零,也不是两个:正好是一个。此驱动程序可在 属性 Driver.

中找到

您将在 属性 Driver 中找到的驱动程序有一个可选的 属性 ProblemSyncToVistracksDriver。这意味着,如果 属性 为空,entity framework 可能会假设没有 ProblemSyncToVistrackDriver 属于此 Driver.

您所做的是,您指定了适当的 one-to-zero-ore-one 关系。每个 Driver 都有零个或一个 ProblemSyncToVistrackDriver,每个 ProblemSyncToVistrackDriver 正好属于一个 Driver.

如果你有一个 Driver,并且你将它的 ProblemSyncToVistrackDriver 设置为零,那么你的意思是这个 Driver 没有 ProblemSyncToVistrackDriver 了。通常,CascadeOnDelete 会注意删除此 Driver 的前 ProblemSyncToVistrackDriver。您指定不希望自动删除,因此 ProblemSyncToVistrackDriver 不会被删除。这就是它没有被删除的原因。

如果您指定要 manual-deletion,则必须自己删除该项目。