Can EF automatically delete data that is orphaned, where the parent is not deleted?

前端 未结 5 1945
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 21:24

For an application using Code First EF 5 beta I have:

public class ParentObject
{
    public int Id {get; set;}
    public virtual List Ch         


        
5条回答
  •  醉话见心
    2020-12-02 22:01

    Want to share another .net ef core solution that worked for me, may be somebody will find it usefull.

    I had a child table with two foreign keys (either or), so the accepted solution didn't work for me. Based on the answer by Marcos Dimitrio I came up with the following:

    In my custom DbContext:

    public override async Task SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
      {
        var modifiedEntities = this.ChangeTracker.Entries().Where(c => c.State == EntityState.Modified);
        foreach (var entityEntry in modifiedEntities)
        {
          if (entityEntry.Entity is ChildObject)
          {
             var fkProperty = entityEntry.Property(nameof(ChildObject.ParentObjectId));
             if (fkProperty.IsModified && fkProperty.CurrentValue == null && fkProperty.OriginalValue != null)
             {
               // Checked if FK was set to NULL
               entityEntry.State = EntityState.Deleted;
             }
          }
        }
    
        return await base.SaveChangesAsync(cancellationToken);
      }
    

提交回复
热议问题