none
How come IsLoaded is failing to recognize a cached entity? RRS feed

  • Question

  • This is probably best explained with two examples:

     

     
    var record = context.MyTable.First();
    var foreignKey = ForeignKeyTable.Where(x => x.Id == record.ForeignKeyId).Single();
    
    var entry = context.Entry(record);
    
    // Returns true
    trace(entry.Reference(x => x.ForeignKey).IsLoaded);
    
    // Doesn't query Db since foreignKey is already cached.
    trace(record.ForeignKey.SomeProperty);
    

    Worked as expected, but this version of essentially the same thing does not:

    var record = context.MyTable.First();
    
    // Creating the foreignKey object instead of querying for it.
    var foreignKey = new ForeignKey() { Id = record.ForeignKeyId, SomeProperty = 5 };
    
    // Attaching it so it is cached.
    context.ForeignKeyTable.Attach(foreignKey);
    
    var entry = context.Entry(record);
    
    // Returns false.
    trace(entry.Reference(x => x.ForeignKey).IsLoaded);
    
    // This gets "5", but doesn't query the db. It must know it's 'loaded' since it didn't hit the db, so how come IsLoaded returns false in this case? How can I test for "IsLoaded" if the entity wasn't tracked to begin with?
    trace(record.ForeignKey.SomeProperty);
    

    What's going on here? How do I test if it's loaded if it doesn't work this way? Thanks for any guidance you can provide.

    Edit: Also, if "IsLoaded" is only really a representation of whether or not it has been loaded from the database, is there any way I could get this kind of functionality: entry.Reference(x => x.ForeignKey).ExistsInContext?

     



    • Edited by Ocelot2020 Thursday, December 15, 2011 9:45 PM
    Thursday, December 15, 2011 9:17 PM

Answers

All replies