Wednesday, 15 June 2011

c# - Return Linq to SQL association objects in list -



c# - Return Linq to SQL association objects in list -

i have next linq sql structure: have classes "article" , "user". each article has seller (which user) , each user has many articles. solved association.

and have method read(), gets articles , returns in list.

public static list<article> read() { using (datacontext dbx = new datacontext()) { homecoming dbx.article.tolist(); } }

so, problem is: when utilize list anywhere in programme , want access article.seller, next exception:

cannot access disposed object

okay, seems legit, because homecoming list , datacontext disposed. if want access seller, loaded database , thats not possible anymore disposed datacontext.

so solved lazy-loading , set deferredloadingenabled property false. load seller, used dataloadoptions.

public static list<article> read() { using (datacontext dbx = new datacontext()) { dbx.deferredloadingenabled = false; dataloadoptions options = new dataloadoptions(); options.loadwith<article>(a => a.seller); dbx.loadoptions = options; homecoming dbx.article.tolist(); } }

okay, works far, in 1 level only. can access article.seller, if i'd other articles of seller (article.seller.articles), null. load articles of seller options.loadwith<user>(u => u.articles); thought, not possible, because endless.

article -> seller -> articles -> each article seller -> articles -> 1 time again seller -> ...

i exception

cycles not allowed in loadoptions loadwith type graph.

what want, method articles right association objects, shown in first method. association objects should accessible, loaded database when accessed.

this possible if utilize datacontext everywhere need list in programme , work list in datacontext. laborious.

have guys thought how access association objects without writing code of read() method everywhere in programme need list?

i have come across in past well. general practice don't phone call dispose() if going allow deferred loading. in fact, calling dispose() not required @ all.

there quite lot written whether or not phone call dispose() on datacontext. you'll have sift through it, there's nice article here. basically, because datacontext manages connections itself, doesn't have connections need disposed explicitly.

c# linq-to-sql

No comments:

Post a Comment