c# - How to Load Association Before Detaching Objects in Entity Framework -


i working parent , child table in entity framework. parent table invoices , child table invoicelineitems. each row in invoice table naturally represents invoice. and, each row in invoicelineitems table represents 1 line of detail invoice (i.e. item information such item name, price, etc...). invoicelineitem table has foreign key invoice table there collection of invoicelineitems on each invoice object.

everything working but, have 1 issue. @ 1 point in our code, build list of invoice objects in detached state. then, insert of objects database using ef data context (now attached session). then, attempting detach invoice objects session can insert invoices database new ef context. when detach invoices, of invoicelineitem collections empty. there way can detach invoices , force bags load before first session closed available second data context? code sample below demonstrate attempting accomplish.

// list of invoices quickbooks list<invoice> qbinvoices = getinvoicesfromquickbooks(currentthread);  saveinvoicestolocaldatabase(dbcontextlocal, qbinvoices, currentthread);  // detach invoices above context can insert them // second database using new context below. // note: invoice.invoicelineitem collections empty //       how force invoicelineitems load??? qbinvoices = dbcontextlocal.invoices.asnotracking().tolist(); dbcontextlocal.dispose();  // saves rows invoices table (i.e. no invoicelineitems saved) saveinvoicestoremotedatabase(dbcontextweb, qbinvoices, currentthread); dbcontextweb.dispose(); 

if i'm understanding correctly, original disconnected invoice entities create have child line items, want unhook them , move them other context. i'm not sure, asnotracking may doing fetch or otherwise creating new instances of entities you've added rather reusing original instances.

i'd suggest casting dbcontext down objectcontext , calling detach method on invoices can moved new context.

instead of:

qbinvoices = dbcontextlocal.invoices.asnotracking().tolist(); dbcontextlocal.dispose(); 

do:

var objectcontext = ((iobjectcontextadapter)context).objectcontext; foreach(var invoice in qbinvoices) {     objectcontext.detach(invoice); } 

Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -