简体   繁体   English

清除FK时删除EF中的实体

[英]Delete an entity in EF when its FK is cleared

Use the following model as an example: 使用以下模型作为示例:

public class Item
{
    public int ItemId { get; set; }
    public int? ScanId { get; set; }
    public Scan Scan { get; set; }
}

public class Scan
{
    public int ScanId { get; set; }
}

Let's say I've associated an instance of Scan to an instance of Item . 假设我已经将Scan的实例与Item的实例相关联。 If I disassociate the Scan record, I want to know if there is a way to configure EF such that it would automatically delete the orphaned Scan record. 如果取消关联Scan记录,我想知道是否有一种方法可以配置EF,以便它可以自动删除孤立的Scan记录。 I believe the concept of cascading deletes does not apply to this situation because it would only pertain to deleting a Scan record if it's Item record was deleted. 我相信级联删除的概念不适用于这种情况,因为它仅适用于在删除Item记录的情况下删除Scan记录的情况。

Thanks in advance. 提前致谢。

How about overriding SaveChanges() ? 覆盖SaveChanges()怎么样? You could check for the modified Item entities, check whether originally the ScanId was not null and now it is null, get the Scan entity for the original ScanId, and then remove it. 您可以检查已修改的Item实体,检查原来的ScanId是否不为null,现在是否为null,获取原始ScanId的Scan实体,然后将其删除。 Something like this: 像这样:

 public override int SaveChanges()
 {
   List<int> orphanedScanIds = new List<int>();
   foreach (var item in this.ChangeTracker.Entries().Where(e => e.Entity is Item && e.State == EntityState.Modified))
   {
      var original = (int?)item.OriginalValues[nameof(Item.ScanId)];
      var current = (int?)item.CurrentValues[nameof(Item.ScanId)];
      if (original.HasValue && !current.HasValue)
      {
          orphanedScans.Add(original.Value);
      }
   }
   var orphanedScans = this.Scans.Where(s => orphanedScans.Contains(s.ScanId)).ToList();
   foreach (var orphanedScan in orphanedScans)
   {
      this.Scans.Remove(orphanedScan);
   }
   return base.SaveChanges();
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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