[英]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.