Entity Framework 4 selective lazy loading properties

后端 未结 4 542
终归单人心
终归单人心 2020-11-30 07:47

Is it possible to load an entity excluding some properties? One of this entity\'s properties is expensive to select. I would like to lazy load this property. Is that possibl

4条回答
  •  既然无缘
    2020-11-30 08:12

    Given a query over an EntityFramework DbSet, where the targeted entity contains a BigProperty and a SmallProperty, When you're trying to only access the SmallProperty without loading the BigProperty in memory :

    //this query loads the entire entity returned by FirstOrDefault() in memory
    //the execution is deferred during Where; the execution happens at FirstOrDefault
    db.BigEntities.Where(filter).FirstOrDefault()?.SmallProperty;
    
    //this query only loads the SmallProperty in memory
    //the execution is still deferred during Select; the execution happens at FirstOrDefault
    //a subset of properties can be selected from the entity, and only those will be loaded in memory
    db.BigEntities.Where(filter).Select(e=>e.SmallProperty).FirstOrDefault();
    

    Therefore you could exploit this behaviour to only query the BigProperty where you actually need it, and use select statements to explicitly filter it out everywhere else.

    I tested this with the Memory Usage functionality from the Visual Studio debug Diagnostic Tools.

提交回复
热议问题