LazyLoadingEnabled setting doesn't seem to work in EF 5

后端 未结 3 557
栀梦
栀梦 2021-01-18 23:49

I\'m using EF Model first with POCO entities and with custom DbContexts. My problem is that setting LazyLoadingEnabled=false does not affect anything, navigatio

3条回答
  •  囚心锁ツ
    2021-01-19 00:40

    The effect you are seeing is called relationship fixup.

    Actually the navigation properties are not loaded explicitly. The query _dbContext.Programs.ToList() only loads the whole Programs table from the database. This is just a simple SQL query (like SELECT * FROM ProgramsTable) without any WHERE clause and without any JOIN to related rows.

    Also no lazy loading happens here (it really can't if you disable it and if you disable even dynamic proxies) when you access the program.Programs and program.OwnerProgram navigation properties.

    The navigation properties get populated when the result from your query is materialized because your query (that loads all programs) will have loaded all programs that the navigation properties can refer to. EF detects that those related entities are already in memory and put them into the navigation properties automatically.

    You can verify this if you don't load all programs but only, for example, a single one:

    Program program  = _dbContext.Programs.FirstOrDefault();
    

    Now, program.Programs and program.OwnerProgram will be null - unless the loaded program is part of its own program.OwnerProgram collection or is its own OwnerProgram.

提交回复
热议问题