1

I have 2 classes:

public class Transaction : AggregateRoot<Guid>
{
    private readonly IList<Correction> _corrections = new List<Correction>();

    public IEnumerable<Correction> Corrections => _corrections;
    public void ClearCorrections()
    {
        _corrections.Clear();
    }
}

public class Correction : Transaction
{
   ....
}

My context is as followed:

    modelBuilder.Entity<Transaction>().HasMany(p => p.Corrections).WithOne().HasForeignKey("ParentTransactionId").OnDelete(DeleteBehavior.NoAction).IsRequired();

When I clear my collection of corrections and db.SaveChanges, database is updated putting ParentTransactionId to null. Instead I would like to delete them from database.

I tried composite key on Correction but EFcore doesn't want as i cannot specify composite Key on a child.

For now, what I do is :

public async Task DeleteCorrectionsAsync(Transaction transaction, CancellationToken cancellationToken)
{
    ....
    foreach (var correction in transaction.Corrections) await Repository.RemoveAsync(correction, cancellationToken);
    
    transaction.ClearCorrections(); 
}

Is there any way i can remove the await Repository.RemoveAsync(correction, cancellationToken); ? I am sure it has been asked 1000 times, but can't find the answer... Thanks !

Tom
  • 944
  • 1
  • 14
  • 26

2 Answers2

2

Clearing a Navigation Property collection does not delete the elements. You could however do

_corrections.ToList().ForEach(e => _corrections.Remove(e))

and then save changes

Malte R
  • 468
  • 5
  • 16
  • I tried this, but i has the same effect, corrections just have their ParentTransactionId set to null – Tom Jul 16 '20 at 09:18
0

Clear() won't affect your database, for this you need to use RemoveRange() from your DbSet. You can find more here.

Nonox
  • 1
  • 1
  • Yes I get that, but I would like to not interact with db set myself, i would like to have EFcore do it with config or something.. no idea how – Tom Jul 16 '20 at 09:20
  • Maybe you can try to use an update on your transaction. Clear your collection from your transaction object, and then use EF to update your transaction object. If your entity is tracked, call SaveChanges() from your transaction DbSet. – Nonox Jul 16 '20 at 09:41
  • Sorry i don't understand, isn't it what I am doing? – Tom Jul 16 '20 at 12:01