Here is some code along with my assumptions based on playing around in LINQPad. Can anyone confirm this is how the lazy loading is working, and perhaps provide any additional insight/links so I can understand how it's working on the back end? Thanks in advance!
// Step 1.
var record = context.MyTable.First();
// Step 2.
var foreignKey = ForeignKeyTable.Where(x => x.Id == record.ForeignKeyId).Single();
// Step 3.
var entry = context.Entry(record);
// Step 4.
trace(entry.Reference(x => x.ForeignKey).IsLoaded);
// Step 5.
trace(record.ForeignKey.SomeProperty);
- Retrieve some record (DB is queried).
- Retrieve a record that happens to be a foreign key property of
record
without using lazy loading likerecord.ForeignKey
to retrieve it (DB is queried). - Get the details of the
record
entity. - This is the part I'm unsure about. In my testing it outputs
true
. I'm guessing that IsLoaded doesn't know whether or notrecord.ForeignKey
currently has a value, but knows thatrecord.ForeignKey
is already being tracked in the context based on it's knowledge ofrecord.ForeignKeyId
and the relationships that have been established. - The db doesn't seem to be hit here, and I assume it's for the same reason
IsLoaded
returns true in 4. It knows that it's tracking theforeignKey
object already, so it knows it doesn't have to do the lazy loading.
Edit: The actual problem I'm trying to solve can be illustrated as such:
var record = context.MyTable.First();
var foreignKey = new ForeignKey() { Id = record.ForeignKeyId, SomeProperty = 5 };
context.ForeignKeyTable.Attach(foreignKey);
var entry = context.Entry(record);
// Returns false.
trace(entry.Reference(x => x.ForeignKey).IsLoaded);
// Doesn't query for ForeignKey, so it must know it's `loaded` somehow, and
// gets SomeProperty from my new foreignKey object. What???
trace(record.ForeignKey.SomeProperty);