2

我首先使用代码并使用以下语句关闭所有外键的级联删除:

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 方法而不是 remove 方法?*

4

1 回答 1

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();
}
于 2011-02-17T00:45:30.727 回答