Entity Framework Core: foreign key was set and is recalled as null

asp.net-core-webapi c# entity-framework-core

Question

I start out by generating a refresh token and storing it in SQL Server via Entity Framework Core as follows:

var refreshToken = new RefreshToken { User = user, Token = Guid.NewGuid().ToString() };
_context.RefreshTokens.Add(refreshToken);
_context.SaveChanges();

_context inherits from Microsoft.EntityFrameworkCore.DbContext.

At this point _context.RefreshTokens.ToList(); has one item in it. Id, Token, and User are all not null and I can access the data in User.

Another API endpoint is called and inside I get the list of RefreshTokens as follows

var l = _context.RefreshTokens.ToList();

l.Id is populated, l.Token is populated, l.User is null.

This poses a problem because I need access to the user associated with the RefreshToken

I have tried getting _context.Users.ToList(); and the user that was set earlier is present in this list.

My initial assumption was that EF might not query for user until it was needed, so I tried to get l.User.Id from the snippet above but it errors as follows.

System.NullReferenceException: Object reference not set to an instance of an object

Why is the field in the entity I just saved null upon recalling it?

1
0
4/14/2020 6:51:51 AM

Accepted Answer

l.Id is populated, l.Token is populated, l.User is null.

l.Id is likely (you do not bother to give us the object definitions) an int or something. l.Token is a Guid, so another primitive type.

l.User is an object. Referenced objects are not loaded unless included (via .Include) ina query. Think about it - if all referenced objects would be automatically loaded, then you would ALWAYS load ALL REFRENCES - which runs down into "the whole database". It is your job to .Include what you want included.

_context.RefreshTokens.Include (x => x.User).ToList()

tells EfCore which included other objects you want to get. You can use multiple includes and includes multiple levels deep. Soon (EfCore 5.0) of with extensions you download from nuget from third parties you can also filter what is loaded via an include.

0
4/14/2020 7:09:17 AM

Popular Answer

Use the Include Method.

_context.RefreshTokens.Include(t => t.User).ToList();

for more reference -> https://docs.microsoft.com/en-us/ef/core/querying/related-data



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow