EF 6 Lazy Loading Disabled but Child Record Loads Anyway

回眸只為那壹抹淺笑 提交于 2019-12-01 06:27:43

is this a problem for you, or are you just curious as to why its happening?

The DBContext keeps track of all references for you. When you load the sections, it knows that the lessons have references to them, and wires it up for you.

you could stop this by disconnecting the objects , or by loading the sections from a different dbcontext

myDbContext.Entry(someLesson).State=Detached;

For the serialization issue, see this Q&A How Do You "Really" Serialize Circular Referencing Objects With Newtonsoft.Json?

or

http://johnnycode.com/2012/04/10/serializing-circular-references-with-json-net-and-entity-framework/

This is, in my opinion, a bad behaviour of EF.

EF works in this way (like probably you already noted): when you disable lazy loading relationships are not resolved (properties are not loaded even if you access the property). In your case you can access to les.LessonSections and you see that is null or (in your case that you initialize it in Lesson constructor) empty.

If you, with the same context access to an object or to a collection not loaded with lazy load (build a query and materialize it) EF automatically try to solve relationships like during lazy load (also if the object does not have a proxy). This is your behavior, in a totally different query you access to LessonSections and EF solves relationships in Lesson.

At first look is a good behaviour but at the end you can have an inconsistent context (some objects with relationships resolved and some other not) and it can result in a buggy app. IMHO, the behaviour could be more consistent if EF (with LazyLoad disabled) doesn't resolve relationships at all and if you need to solve it you do it by hand. But is just my opinion.

About your question you can detach the object like suggested in another answer or use two different contexts (with the same or a different connection) in the same unit of work. I prefere (usually I use) this second approach disposing the context with Lazy Load disabled as soon as possible.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!