2011-02-16 40 views
2

我第一次使用的代码和关闭级联使用下面的语句删除全部夷键:使用EF4 CTP5代码第一个不使用级联删除

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

我有两个类发票和InvoiceLine

0123:
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

尝试也是从集合中删除发票发票行。 – 2011-02-16 17:00:50

+0

@Ladislav Mrnka:既不工作也不工作 – Gregoire 2011-02-16 17:11:41

回答

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