简体   繁体   English

EntityFramework 核心:当集合被继承 class 时,清除集合不会正确反映在数据库中

[英]EntityFramework Core: Clearing collection doesn't not reflect propertly in database when collection is inherited class

I have 2 classes:我有 2 节课:

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.当我清除我的更正集合和 db.SaveChanges 时,数据库会更新,将 ParentTransactionId 设置为 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.我在 Correction 上尝试了复合键,但 EFcore 不想要,因为我无法在孩子上指定复合键。

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);有什么办法可以删除 await Repository.RemoveAsync(correction, cancelToken); ? ? I am sure it has been asked 1000 times, but can't find the answer... Thanks !我敢肯定它已经被问了 1000 次,但找不到答案……谢谢!

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. Clear()不会影响您的数据库,为此您需要使用RemoveRange() You can find more here .你可以在这里找到更多。

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

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