EF Core returns null relations until direct access












12














I have some models like those below:



public class Mutant
{
public long Id { get; set; }
...

// Relations
public long OriginalCodeId { get; set; }
public virtual OriginalCode OriginalCode { get; set; }
public int DifficultyLevelId { get; set; }
public virtual DifficultyLevel DifficultyLevel { get; set; }
}


and



public class OriginalCode
{
public long Id { get; set; }
...

// Relations
public virtual List<Mutant> Mutants { get; set; }
public virtual List<OriginalCodeInputParameter> OriginalCodeInputParameters { get; set; }
}


and in the OnModelCreating of DBContext I made the relations like these:



        modelBuilder.Entity<Mutant>()
.HasOne(m => m.OriginalCode)
.WithMany(oc => oc.Mutants)
.HasForeignKey(m => m.OriginalCodeId)
.OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Restrict);

modelBuilder.Entity<Mutant>()
.HasOne(m => m.DifficultyLevel)
.WithMany(dl => dl.Mutants)
.HasForeignKey(m => m.DifficultyLevelId)
.OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Restrict);


now when I request for Mutants, the OriginalCode is null:



Null OriginalCode



but as soon as I request for OriginalCodes like below:



OriginalCodes



then the OriginalCode field of the mutants will be not null:



Filled Object



What is the reason and how could I fix it?










share|improve this question





























    12














    I have some models like those below:



    public class Mutant
    {
    public long Id { get; set; }
    ...

    // Relations
    public long OriginalCodeId { get; set; }
    public virtual OriginalCode OriginalCode { get; set; }
    public int DifficultyLevelId { get; set; }
    public virtual DifficultyLevel DifficultyLevel { get; set; }
    }


    and



    public class OriginalCode
    {
    public long Id { get; set; }
    ...

    // Relations
    public virtual List<Mutant> Mutants { get; set; }
    public virtual List<OriginalCodeInputParameter> OriginalCodeInputParameters { get; set; }
    }


    and in the OnModelCreating of DBContext I made the relations like these:



            modelBuilder.Entity<Mutant>()
    .HasOne(m => m.OriginalCode)
    .WithMany(oc => oc.Mutants)
    .HasForeignKey(m => m.OriginalCodeId)
    .OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Restrict);

    modelBuilder.Entity<Mutant>()
    .HasOne(m => m.DifficultyLevel)
    .WithMany(dl => dl.Mutants)
    .HasForeignKey(m => m.DifficultyLevelId)
    .OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Restrict);


    now when I request for Mutants, the OriginalCode is null:



    Null OriginalCode



    but as soon as I request for OriginalCodes like below:



    OriginalCodes



    then the OriginalCode field of the mutants will be not null:



    Filled Object



    What is the reason and how could I fix it?










    share|improve this question



























      12












      12








      12


      3





      I have some models like those below:



      public class Mutant
      {
      public long Id { get; set; }
      ...

      // Relations
      public long OriginalCodeId { get; set; }
      public virtual OriginalCode OriginalCode { get; set; }
      public int DifficultyLevelId { get; set; }
      public virtual DifficultyLevel DifficultyLevel { get; set; }
      }


      and



      public class OriginalCode
      {
      public long Id { get; set; }
      ...

      // Relations
      public virtual List<Mutant> Mutants { get; set; }
      public virtual List<OriginalCodeInputParameter> OriginalCodeInputParameters { get; set; }
      }


      and in the OnModelCreating of DBContext I made the relations like these:



              modelBuilder.Entity<Mutant>()
      .HasOne(m => m.OriginalCode)
      .WithMany(oc => oc.Mutants)
      .HasForeignKey(m => m.OriginalCodeId)
      .OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Restrict);

      modelBuilder.Entity<Mutant>()
      .HasOne(m => m.DifficultyLevel)
      .WithMany(dl => dl.Mutants)
      .HasForeignKey(m => m.DifficultyLevelId)
      .OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Restrict);


      now when I request for Mutants, the OriginalCode is null:



      Null OriginalCode



      but as soon as I request for OriginalCodes like below:



      OriginalCodes



      then the OriginalCode field of the mutants will be not null:



      Filled Object



      What is the reason and how could I fix it?










      share|improve this question















      I have some models like those below:



      public class Mutant
      {
      public long Id { get; set; }
      ...

      // Relations
      public long OriginalCodeId { get; set; }
      public virtual OriginalCode OriginalCode { get; set; }
      public int DifficultyLevelId { get; set; }
      public virtual DifficultyLevel DifficultyLevel { get; set; }
      }


      and



      public class OriginalCode
      {
      public long Id { get; set; }
      ...

      // Relations
      public virtual List<Mutant> Mutants { get; set; }
      public virtual List<OriginalCodeInputParameter> OriginalCodeInputParameters { get; set; }
      }


      and in the OnModelCreating of DBContext I made the relations like these:



              modelBuilder.Entity<Mutant>()
      .HasOne(m => m.OriginalCode)
      .WithMany(oc => oc.Mutants)
      .HasForeignKey(m => m.OriginalCodeId)
      .OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Restrict);

      modelBuilder.Entity<Mutant>()
      .HasOne(m => m.DifficultyLevel)
      .WithMany(dl => dl.Mutants)
      .HasForeignKey(m => m.DifficultyLevelId)
      .OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Restrict);


      now when I request for Mutants, the OriginalCode is null:



      Null OriginalCode



      but as soon as I request for OriginalCodes like below:



      OriginalCodes



      then the OriginalCode field of the mutants will be not null:



      Filled Object



      What is the reason and how could I fix it?







      entity-framework-core






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 13 '18 at 4:31









      Cœur

      17.4k9103145




      17.4k9103145










      asked Feb 19 '17 at 13:03









      ConductedCleverConductedClever

      1,2381135




      1,2381135
























          1 Answer
          1






          active

          oldest

          votes


















          27














          The reason is explained in the Loading Related Data section of the EF Core documentation.



          The first behavior is because EF Core currently does not support lazy loading, so normally you'll get null for navigation properties until you specifically load them via eager or explicit loading. However, the Eager loading section contains the following:




          Tip

          Entity Framework Core will automatically fix-up navigation properties to any other entities that were previously loaded into the context instance. So even if you don't explicitly include the data for a navigation property, the property may still be populated if some or all of the related entities were previously loaded.




          which explains why the navigation property is not null in the second case.



          Now, I'm not sure which of the two behaviors do you want to fix, so will try to address both.



          The first behavior can be "fixed" by using one of the currently available methods for loading related data, for instance eager loading:



          var mutants = db.Mutants.Include(m => m.OriginalCode).ToList();


          The second behavior is "by design" and cannot be controlled. If you want to avoid it, make sure to use fresh new DbContext instance just for executing a single query to retry the data needed.



          Update: Starting with v2.1, EF Core supports Lazy Loading. However it's not enabled by default, so in order to utilize it one should mark all navigation properties virtual, install Microsoft.EntityFrameworkCore.Proxies and enable it via UseLazyLoadingProxies call, or utilize Lazy-loading without proxies - both explained with examples in the EF Core documentation.






          share|improve this answer



















          • 1




            As you could guess I want to control the first behavior. But there is still a big question. This way you mentioned, I should explicitly address the relations to be filled, true?
            – ConductedClever
            Feb 19 '17 at 15:51










          • Indeed. You have to specify each one you want to be "included" using several Include / ThenInclude methods. AFAIK there are some plans for making this automatically in the future, but for now that's the only option.
            – Ivan Stoev
            Feb 19 '17 at 16:02










          • What about guessing, one never knows - for instance see a few question before yours in EF Core tag - Can I stop Entity Framework Core from populating my result with partial data? :)
            – Ivan Stoev
            Feb 19 '17 at 16:08








          • 1




            :) Thanks. Very Helpfull answer.
            – ConductedClever
            Feb 19 '17 at 16:50






          • 1




            Now EF Core support lazy loading: docs.microsoft.com/en-us/ef/core/querying/…
            – Pejman.Nik
            Apr 22 '18 at 13:41













          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f42327515%2fef-core-returns-null-relations-until-direct-access%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          27














          The reason is explained in the Loading Related Data section of the EF Core documentation.



          The first behavior is because EF Core currently does not support lazy loading, so normally you'll get null for navigation properties until you specifically load them via eager or explicit loading. However, the Eager loading section contains the following:




          Tip

          Entity Framework Core will automatically fix-up navigation properties to any other entities that were previously loaded into the context instance. So even if you don't explicitly include the data for a navigation property, the property may still be populated if some or all of the related entities were previously loaded.




          which explains why the navigation property is not null in the second case.



          Now, I'm not sure which of the two behaviors do you want to fix, so will try to address both.



          The first behavior can be "fixed" by using one of the currently available methods for loading related data, for instance eager loading:



          var mutants = db.Mutants.Include(m => m.OriginalCode).ToList();


          The second behavior is "by design" and cannot be controlled. If you want to avoid it, make sure to use fresh new DbContext instance just for executing a single query to retry the data needed.



          Update: Starting with v2.1, EF Core supports Lazy Loading. However it's not enabled by default, so in order to utilize it one should mark all navigation properties virtual, install Microsoft.EntityFrameworkCore.Proxies and enable it via UseLazyLoadingProxies call, or utilize Lazy-loading without proxies - both explained with examples in the EF Core documentation.






          share|improve this answer



















          • 1




            As you could guess I want to control the first behavior. But there is still a big question. This way you mentioned, I should explicitly address the relations to be filled, true?
            – ConductedClever
            Feb 19 '17 at 15:51










          • Indeed. You have to specify each one you want to be "included" using several Include / ThenInclude methods. AFAIK there are some plans for making this automatically in the future, but for now that's the only option.
            – Ivan Stoev
            Feb 19 '17 at 16:02










          • What about guessing, one never knows - for instance see a few question before yours in EF Core tag - Can I stop Entity Framework Core from populating my result with partial data? :)
            – Ivan Stoev
            Feb 19 '17 at 16:08








          • 1




            :) Thanks. Very Helpfull answer.
            – ConductedClever
            Feb 19 '17 at 16:50






          • 1




            Now EF Core support lazy loading: docs.microsoft.com/en-us/ef/core/querying/…
            – Pejman.Nik
            Apr 22 '18 at 13:41


















          27














          The reason is explained in the Loading Related Data section of the EF Core documentation.



          The first behavior is because EF Core currently does not support lazy loading, so normally you'll get null for navigation properties until you specifically load them via eager or explicit loading. However, the Eager loading section contains the following:




          Tip

          Entity Framework Core will automatically fix-up navigation properties to any other entities that were previously loaded into the context instance. So even if you don't explicitly include the data for a navigation property, the property may still be populated if some or all of the related entities were previously loaded.




          which explains why the navigation property is not null in the second case.



          Now, I'm not sure which of the two behaviors do you want to fix, so will try to address both.



          The first behavior can be "fixed" by using one of the currently available methods for loading related data, for instance eager loading:



          var mutants = db.Mutants.Include(m => m.OriginalCode).ToList();


          The second behavior is "by design" and cannot be controlled. If you want to avoid it, make sure to use fresh new DbContext instance just for executing a single query to retry the data needed.



          Update: Starting with v2.1, EF Core supports Lazy Loading. However it's not enabled by default, so in order to utilize it one should mark all navigation properties virtual, install Microsoft.EntityFrameworkCore.Proxies and enable it via UseLazyLoadingProxies call, or utilize Lazy-loading without proxies - both explained with examples in the EF Core documentation.






          share|improve this answer



















          • 1




            As you could guess I want to control the first behavior. But there is still a big question. This way you mentioned, I should explicitly address the relations to be filled, true?
            – ConductedClever
            Feb 19 '17 at 15:51










          • Indeed. You have to specify each one you want to be "included" using several Include / ThenInclude methods. AFAIK there are some plans for making this automatically in the future, but for now that's the only option.
            – Ivan Stoev
            Feb 19 '17 at 16:02










          • What about guessing, one never knows - for instance see a few question before yours in EF Core tag - Can I stop Entity Framework Core from populating my result with partial data? :)
            – Ivan Stoev
            Feb 19 '17 at 16:08








          • 1




            :) Thanks. Very Helpfull answer.
            – ConductedClever
            Feb 19 '17 at 16:50






          • 1




            Now EF Core support lazy loading: docs.microsoft.com/en-us/ef/core/querying/…
            – Pejman.Nik
            Apr 22 '18 at 13:41
















          27












          27








          27






          The reason is explained in the Loading Related Data section of the EF Core documentation.



          The first behavior is because EF Core currently does not support lazy loading, so normally you'll get null for navigation properties until you specifically load them via eager or explicit loading. However, the Eager loading section contains the following:




          Tip

          Entity Framework Core will automatically fix-up navigation properties to any other entities that were previously loaded into the context instance. So even if you don't explicitly include the data for a navigation property, the property may still be populated if some or all of the related entities were previously loaded.




          which explains why the navigation property is not null in the second case.



          Now, I'm not sure which of the two behaviors do you want to fix, so will try to address both.



          The first behavior can be "fixed" by using one of the currently available methods for loading related data, for instance eager loading:



          var mutants = db.Mutants.Include(m => m.OriginalCode).ToList();


          The second behavior is "by design" and cannot be controlled. If you want to avoid it, make sure to use fresh new DbContext instance just for executing a single query to retry the data needed.



          Update: Starting with v2.1, EF Core supports Lazy Loading. However it's not enabled by default, so in order to utilize it one should mark all navigation properties virtual, install Microsoft.EntityFrameworkCore.Proxies and enable it via UseLazyLoadingProxies call, or utilize Lazy-loading without proxies - both explained with examples in the EF Core documentation.






          share|improve this answer














          The reason is explained in the Loading Related Data section of the EF Core documentation.



          The first behavior is because EF Core currently does not support lazy loading, so normally you'll get null for navigation properties until you specifically load them via eager or explicit loading. However, the Eager loading section contains the following:




          Tip

          Entity Framework Core will automatically fix-up navigation properties to any other entities that were previously loaded into the context instance. So even if you don't explicitly include the data for a navigation property, the property may still be populated if some or all of the related entities were previously loaded.




          which explains why the navigation property is not null in the second case.



          Now, I'm not sure which of the two behaviors do you want to fix, so will try to address both.



          The first behavior can be "fixed" by using one of the currently available methods for loading related data, for instance eager loading:



          var mutants = db.Mutants.Include(m => m.OriginalCode).ToList();


          The second behavior is "by design" and cannot be controlled. If you want to avoid it, make sure to use fresh new DbContext instance just for executing a single query to retry the data needed.



          Update: Starting with v2.1, EF Core supports Lazy Loading. However it's not enabled by default, so in order to utilize it one should mark all navigation properties virtual, install Microsoft.EntityFrameworkCore.Proxies and enable it via UseLazyLoadingProxies call, or utilize Lazy-loading without proxies - both explained with examples in the EF Core documentation.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jul 9 '18 at 18:02

























          answered Feb 19 '17 at 15:24









          Ivan StoevIvan Stoev

          100k770125




          100k770125








          • 1




            As you could guess I want to control the first behavior. But there is still a big question. This way you mentioned, I should explicitly address the relations to be filled, true?
            – ConductedClever
            Feb 19 '17 at 15:51










          • Indeed. You have to specify each one you want to be "included" using several Include / ThenInclude methods. AFAIK there are some plans for making this automatically in the future, but for now that's the only option.
            – Ivan Stoev
            Feb 19 '17 at 16:02










          • What about guessing, one never knows - for instance see a few question before yours in EF Core tag - Can I stop Entity Framework Core from populating my result with partial data? :)
            – Ivan Stoev
            Feb 19 '17 at 16:08








          • 1




            :) Thanks. Very Helpfull answer.
            – ConductedClever
            Feb 19 '17 at 16:50






          • 1




            Now EF Core support lazy loading: docs.microsoft.com/en-us/ef/core/querying/…
            – Pejman.Nik
            Apr 22 '18 at 13:41
















          • 1




            As you could guess I want to control the first behavior. But there is still a big question. This way you mentioned, I should explicitly address the relations to be filled, true?
            – ConductedClever
            Feb 19 '17 at 15:51










          • Indeed. You have to specify each one you want to be "included" using several Include / ThenInclude methods. AFAIK there are some plans for making this automatically in the future, but for now that's the only option.
            – Ivan Stoev
            Feb 19 '17 at 16:02










          • What about guessing, one never knows - for instance see a few question before yours in EF Core tag - Can I stop Entity Framework Core from populating my result with partial data? :)
            – Ivan Stoev
            Feb 19 '17 at 16:08








          • 1




            :) Thanks. Very Helpfull answer.
            – ConductedClever
            Feb 19 '17 at 16:50






          • 1




            Now EF Core support lazy loading: docs.microsoft.com/en-us/ef/core/querying/…
            – Pejman.Nik
            Apr 22 '18 at 13:41










          1




          1




          As you could guess I want to control the first behavior. But there is still a big question. This way you mentioned, I should explicitly address the relations to be filled, true?
          – ConductedClever
          Feb 19 '17 at 15:51




          As you could guess I want to control the first behavior. But there is still a big question. This way you mentioned, I should explicitly address the relations to be filled, true?
          – ConductedClever
          Feb 19 '17 at 15:51












          Indeed. You have to specify each one you want to be "included" using several Include / ThenInclude methods. AFAIK there are some plans for making this automatically in the future, but for now that's the only option.
          – Ivan Stoev
          Feb 19 '17 at 16:02




          Indeed. You have to specify each one you want to be "included" using several Include / ThenInclude methods. AFAIK there are some plans for making this automatically in the future, but for now that's the only option.
          – Ivan Stoev
          Feb 19 '17 at 16:02












          What about guessing, one never knows - for instance see a few question before yours in EF Core tag - Can I stop Entity Framework Core from populating my result with partial data? :)
          – Ivan Stoev
          Feb 19 '17 at 16:08






          What about guessing, one never knows - for instance see a few question before yours in EF Core tag - Can I stop Entity Framework Core from populating my result with partial data? :)
          – Ivan Stoev
          Feb 19 '17 at 16:08






          1




          1




          :) Thanks. Very Helpfull answer.
          – ConductedClever
          Feb 19 '17 at 16:50




          :) Thanks. Very Helpfull answer.
          – ConductedClever
          Feb 19 '17 at 16:50




          1




          1




          Now EF Core support lazy loading: docs.microsoft.com/en-us/ef/core/querying/…
          – Pejman.Nik
          Apr 22 '18 at 13:41






          Now EF Core support lazy loading: docs.microsoft.com/en-us/ef/core/querying/…
          – Pejman.Nik
          Apr 22 '18 at 13:41




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f42327515%2fef-core-returns-null-relations-until-direct-access%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

          SQL update select statement

          'app-layout' is not a known element: how to share Component with different Modules