2

We are facing a problem on EF. While lazy loading, sometimes the navigation property is returning null.

Note: I made this.Configuration.LazyLoadingEnabled = true; on the db context

Model:

public class Student
{
    public Int64 Id { get; set; }
    public string Name { get; set; }
    public string Gender { get; set; }

    public Int64 Address_Id { get; set; }

    [ForeignKey("Address_Id")]
    public virtual Address Address { get; set; }
}

public class Address
{
    public Int64 Id { get; set; }
    public string Name { get; set; }
}

Database access:

Student oStudnet = context.Students.FirstOrDefault();
Int64 addressId= oStudnet.Address.Id  

"null exception" on "oStudnet.Address.id" // Address is null here

Lalit C
  • 51
  • 5
  • 1
    I am afraid your code here is oversimplified and the actual reason that this happens is omitted as a result. As of the code posted here, this should not happen (well, I am pretty sure you think the same :) ) Could you please provide a bit more context? For example, maybe you are using the `.AsNoTracking()` extension somewhere explicitly or hidden by another helper that you've written. – Balázs Oct 17 '17 at 07:10
  • [Log the generated SQL](https://stackoverflow.com/questions/1412863/how-do-i-view-the-sql-generated-by-the-entity-framework) and check it against the database. – Steve Greene Oct 17 '17 at 13:45
  • I have the same problem. I added optionsBuilder.UseLazyLoadingProxies(); to Context.OnConfiguring(DbContextOptionsBuilder optionsBuilder) and I get 'System.InvalidOperationException' on all of my naviguation property unless I debug it step by step. – Michaël Corriveau-Côté May 17 '19 at 14:14

1 Answers1

-2
Student oStudnet = context.Students.Include("Address").FirstOrDefault();

Then you can access the address

Stefan PEev
  • 481
  • 5
  • 17
  • Thanks for your answer, Unsderstood **Include(Eager loading)** will work out. We have the use case of **lazy loading**, i attached a sample code only. – Lalit C Oct 17 '17 at 06:50