![](/img/trans.png)
[英]EntityFramework Core Database.EnsureCreated doesn't create database
[英]EntityFramework Core: Clearing collection doesn't not reflect propertly in database when collection is inherited class
我有 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
{
....
}
我的上下文如下:
modelBuilder.Entity<Transaction>().HasMany(p => p.Corrections).WithOne().HasForeignKey("ParentTransactionId").OnDelete(DeleteBehavior.NoAction).IsRequired();
当我清除我的更正集合和 db.SaveChanges 时,数据库会更新,将 ParentTransactionId 设置为 null。 相反,我想从数据库中删除它们。
我在 Correction 上尝试了复合键,但 EFcore 不想要,因为我无法在孩子上指定复合键。
目前,我要做的是:
public async Task DeleteCorrectionsAsync(Transaction transaction, CancellationToken cancellationToken)
{
....
foreach (var correction in transaction.Corrections) await Repository.RemoveAsync(correction, cancellationToken);
transaction.ClearCorrections();
}
有什么办法可以删除 await Repository.RemoveAsync(correction, cancelToken); ? 我敢肯定它已经被问了 1000 次,但找不到答案……谢谢!
清除导航属性集合不会删除元素。 但是你可以这样做
_corrections.ToList().ForEach(e => _corrections.Remove(e))
然后保存更改
Clear()
不会影响您的数据库,为此您需要使用RemoveRange()
。 你可以在这里找到更多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.