Search code examples
entity-frameworkforeign-keysnullreferenceexceptionasp.net-core-identity

ASP.NET Core: NullReferenceException on getting foreign key


I am working on a booking system for computer club.

I am getting NullReferenceException when I try to get a foreign key of an instance.

Example:

var queue = _db.Queues.First(q => q.Index == 1);
Console.WriteLine(queue.QueueId); // works fine (primary key)
Console.WriteLine(queue.Index); // works fine (simple property)
Console.WriteLine(queue.User.Id); // NullReferenceException (foreign key)

The queue itself, obviously, is not null but queue.User is null. How's that possible?


Solution

  • Try to use Include in your EF core query.Refer to Loading related data.

    using Microsoft.EntityFrameworkCore;
    
    var queue =_db.Queues.Include(q => q.User).First(q => q.Index == 1);