Book Image

Learning .NET High-performance Programming

By : Antonio Esposito
Book Image

Learning .NET High-performance Programming

By: Antonio Esposito

Overview of this book

Table of Contents (16 chapters)
Learning .NET High-performance Programming
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Entity Framework persistence optimization


When dealing with DML statements, EF shows some limitations due to its object orientation. An example on all comes with a DELETE statement made in EF. This example shows how to make a master-detail delete operation:

int InvoiceID = 11;

using (var db = new InvoicingDBContainer())
{
    //materialize an invoice
    //this will produce a SELECT statement
    var invoice = db.Invoice
        .Include("InvoiceElement") //eager-load elements for deletion
        .FirstOrDefault(x => x.InvoiceID == InvoiceID);

    //manually load elements for deletion
    //no lazy-load works for cascade delete objects
    //db.Entry(invoice).Collection("InvoiceElement").Load();

    //informs EF context to remove invoice from database
    db.Invoice.Remove(invoice);

    //asks EF context to persist changed entities
    //this will produce the DELETE statement
    db.SaveChanges();
}

Obviously, the whole selection of the Invoice and of all InvoiceElement instances ...