I'm using EF6 code first. There are two tables, Lesson
and LessonSections
. The LessonSections
table has a foreign key to Lesson.Id
Here is the Lesson
class with none important fields removed:
public partial class Lesson
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Lesson()
{
LessonSections = new HashSet<LessonSection>();
}
[StringLength(50)]
public string Id { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<LessonSection> LessonSections { get; set; }
}
Here is how I'm initiating my data model:
var db = new Touch_Type_Trainer_DB.DataModel();
db.Configuration.ProxyCreationEnabled = false;
db.Configuration.LazyLoadingEnabled = false;
Just after my first call to the database to retrieve the first lesson in the database, the resulting object has no LessonSections
Then I make a second call to retrieve the sections into a separate object. (They must be in a separate objects since I want to serialize them to a JSON string and the serializer halts on the circular reference between Lesson
and LessonSections
if I use the standard EF LazyLoading.)
Now my original object has two sections loaded from the database even though I never accessed the LessonSections
property and even though LazyLoadingEnabled is set to False!
Why do the LessonSections
get loaded?
Edit:
I'm using Newtonsoft to serialize my object into a JSON string. Maybe there is a configuration setting in Newtonsoft that I should be setting so it doesn't get caught in the circular reference problem?
Also, I do want LazyLoading enabled for the majority of the code, just not for the serializing part.