Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF4 Code First: Lazy Loading Issue

On the web site I am currently working on I decided to give EF4 Code First a shot. It doesn't seem to bad, although not supporting enums means the impressive points are negated by a simple short coming.

Anyway, the problem I have now is that I have a book object which has a collection of authors. When I click on a page where the book is reviewed - an error gets thrown when the book's authors cannot be added to the viewdata - saying the author's collection for this book is null.

so, I navigate to the administration page, go to edit the book, and then suddenly the authors re-appear. So i navigate back to the review page and the authors now appear on this page too.

It looks like they aren't being loaded the first time, but for some reason the admin section causes them to load, so when I head back to the review page it all works fine.

If i happen to do a recompile, and go straight to the review page, they're gone again.

I'm getting my books from the context using CreateObject set - via repository. This method is used both on the admin page and also the review page.

thanks if you are able to help.

like image 845
nick Avatar asked Jan 21 '23 13:01

nick


1 Answers

To allow lazy loading on POCO class you have to mark your navigation properties as virtual. To force eager loading modify query in your repository and use something like Include("Authors") on queryed ObjectSet.

like image 108
Ladislav Mrnka Avatar answered Apr 28 '23 13:04

Ladislav Mrnka