Search code examples
c#asp.net-coreentity-framework-core

How to get Complex object with EFcore using foreign key?


I am using asp net core 5 for developing web API! I have a problem that i create my database with EFCORE and I want to query an object that has foreign key!

Here is my code:

public long RefreshTokenId { get; set; }
public string JwtTokenId { get; set;}
public User user { get; set; }
public Int64 expirationTime { get; set; }
public string Token { get; set; }
public bool Revoked { get; set; }

In this class I use User Object as an object with foreign key in one to one relation according to efcore documentation!

Here is my problem:

public async Task<long> RefreshToken(RefreshRequest refreshRequest)
{
RefreshToken refreshToken = await Task.Run(() => {
    return _appContext.refreshTokens.SingleOrDefault(x => x.Token ==  
         refreshRequest.refreshToken);
});

 return refreshToken.user.UserId;
 }

When I run this function the null pointer exception is thrown! Can anybody explain me how to retrieve user object with efcore?


Solution

  • the main issue is that i wanted to load related data with foreign key and it has three methods and the following links would help you!

    from MicroSoft Docs from tutorials in internnt!