Using include doesn't change the behavior

前端 未结 4 782
甜味超标
甜味超标 2020-12-20 21:47

Could Someone help me to clarify the difference between :

 var query = awlt.People.Include(p => p.EmailAddresses)
                    .Where(p => p.Las         


        
4条回答
  •  无人及你
    2020-12-20 22:11

    Don't know about EF 7, but in EF 6 both those statements produce the same queries to database and so are essentially the same. There is no lazy loading, no eager loading (in a sense this term is usually used) whatsoever.

    You need to Include only properties of entities you materialize. In the example above you materialize Person.EmailAddresses.EmailAddress1, but you include just Person.EmailAddresses - this has no effect (for more details see for example here).

    Consider this sample code (details does not matter, there is just Error entity with Code navigation property):

    // note we materialized query 
    var errors = ctx.Errors.Include(c => c.Code).ToArray();
    // no lazy loading happens here - we already loaded all related Codes with Include
    var codeIds = errors.Select(c => c.Code.CodeID).ToArray();
    

    And this one:

    // no need to include here!
    var codeIds = ctx.Errors.Select(c =>c.Code.CodeID).ToArray();
    

    And with include:

    // include has no effect here!
    var codeIds = ctx.Errors.Inlcude(c => c.Code).Select(c => c.Code.CodeID).ToArray();
    

    What is eager loading? It's when you include additional data to the related entity using Include statement. Here Include statement has no effect, it's just does nothing, so we cannot name that eager loading.

    What is lazy loading? It's when navigation property is loading when you access it for the first time. You do not do this in your examples, so there is no lazy loading either.

    Both examples just execute identical queries to database (after you materialize them with enumeration`ToArray` etc).

提交回复
热议问题