我使用以下语句首先使用代码,关闭所有foreigns键的级联删除:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
我有两个班级Invoice和InvoiceLine
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? * 为什么我必须为invoicelines调用DeleteObject方法而不是删除它? *
答案 0 :(得分:0)
试试吧
public void DeleteInvoice(Guid id) {
var invoice = this.SelectInvoiceById(id, i => i.InvoiceLines);
foreach(var line in invoice.InvoiceLines) {
this.DataContext.InvoiceLine.Remove(line);
}
this.DataContext.Invoices.Remove(invoice)
this.DataContext.SaveChanges();
}