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 !
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
Clear()
won't affect your database, for this you need to use RemoveRange()
from your DbSet. You can find more here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.