最初にコードを使用し、次のステートメントを使用してすべての外部キーのカスケード削除をオフにしました。
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
Invoice と InvoiceLine の 2 つのクラスがあります。
public class Invoice : ITrackable
{
[Key]
public Guid Id { get; set; }
public virtual ICollection<InvoiceLine> InvoiceLines { get; set; }
//other properties
}
public class InvoiceLine : ITrackable
{
[Key]
public Guid Id { get; set; }
public Guid InvoiceId { get; set; }
[ForeignKey("InvoiceId")]
public virtual Invoice Invoice { get; set; }
//other properties
}
請求書とそれに関連するすべての請求書明細を削除したい場合に問題が発生します。次のコードは機能します。
public IQueryable<Invoice> SelectAllInvoices(params Expression<Func<Invoice, object>>[] includes)
{
DbQuery<Invoice> result = this.DataContext.Invoices;
foreach (var include in includes)
{
result = result.Include(include);
}
return result;
}
public Invoice SelectInvoiceById(Guid id, params Expression<Func<Invoice, object>>[] includes)
{
return this.SelectAllInvoices(includes).FirstOrDefault(invoice => invoice.Id == id);
}
public void DeleteInvoice(Guid id)
{
var invoice = this.SelectInvoiceById(id, i => i.InvoiceLines);
for (int index = 0; index < invoice.InvoiceLines.Count; index++)
{
var line = invoice.InvoiceLines.ElementAt(index);
this.DataContext.DeleteObject(line);
this.DataContext.SaveChanges();
}
this.DataContext.Invoices.Remove(invoice);
this.DataContext.SaveChanges();
}
しかし、for ループで SaveChanges アクションを削除すると機能しません。
中間の SaveChanges を実行する必要があるのはなぜですか? *また、なぜ請求書の削除ではなく、請求書の DeleteObject メソッドを呼び出さなければならないのでしょうか? *