开发者

EF4 Code First: Lazy Loading Issue

开发者 https://www.devze.com 2023-01-13 01:21 出处:网络
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 n开发者_开发问答ot supporting enums means the impressive points are negated by a si

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 n开发者_开发问答ot 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.


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.


Just done a little more investigation and I know why it works on the admin page. After debugging through, I found the book's authors collection is initially null. But when a select list is rendered, that contains all the author's in the system, then it gets its authors collection populated.

So in my review action, I retrieve all authors from the repository, without using them in any way, and then my book's collection is also populated.

I guess all this waffling leads to the question: How can I fix lazy loading, or how can I ensure eager loading. I don't think performance will ever be critical and I've had enough faffing with code first now. Think I'll stick to Active record/nhibernate for the time being on other projects.

0

精彩评论

暂无评论...
验证码 换一张
取 消