Problem by Lazy loading in entity framework -
i have 2 entities in 1:n relationship: link, category. @ first categories , links , put them list. next fill links of every category manually category.links.add(link)
connect db , link again , cause double data in result. know action because of lazy loading. lazy loading true , not want disable it. how can fill links of every category manually without connecting db again? please not offer eager loading or disabeling lazy load.
var categories = categoryrepository.getcategories().tolist(); var alllinks = linkrepository.getlinks().tolist(); foreach (var category in categories) { var links = alllinks.where(l => l.categoryid == category.categoryid); foreach (var link in links) { category.links.add(link); } }
even mentioned don't want turn off lazy loading insists because lazy loading triggered when access navigation property first time. way avoid is:
- turning lazy loading off. disadvantage must turn lazy loading off whole processing of categories. because once turn on reload
links
during next access property. reasonentitycollection
used handlinglinks
has propertyisloaded
false (and cannot modified except callingload
). - removing
virtual
keywordlinks
collection. disallow wrappingcategory
dynamic proxy , because of not allow lazy loading. more interesting because needed code in loading should first 2 lines - links populated categories automatically during second query execution. problem here removing virtual keyword auto generated entities hard (it must hard coded t4 template) or must use own entity. - somehow cheating ef replacing
entitycollection
inlinks
property collection. not easy because can't assign new collectionlinks
- dynamic proxy throwinvalidoperationexception
. must create second partial part of entity , add code modify directly private field holding collection (bypassing property). such approach can have bad consequences. default code uses fixups etc.
turning lazy loading off not break functionality - ef doing quite internally. need do:
context.contextoptions.lazyloadingenabled = false;
Comments
Post a Comment