开发者

Using EF4 CTP5 code first with no cascade delete

开发者 https://www.devze.com 2023-02-11 02:10 出处:网络
I\'m using code first and turned off the cascade delete for all foreigns keys using the following statement:

I'm using code first and turned off the cascade delete for all foreigns keys using the following statement:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}

I have two classes Invoice and 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 properti开发者_如何学运维es
}

The problem occurs when I want to delete an invoice and all its related invoice lines The following code works:

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();
}

but when I delete the SaveChanges action in the for loop it does not works.

Why do I have to perform intermediate SaveChanges ? *And why do I have to call DeleteObject method for invoicelines and not the remove one?*


try it

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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消