0

I have two tables: Users and Tokens like below.

enter image description here

Now I write query using EF, it take Token object, but subobject User inside Token object is null. How should I modify my query to get Token with User object?

using (var db = new AccountDbContext())
{
    Token tok = db.Tokens
       .FirstOrDefault(p => tokenValue == p.Value) == 0);

    if (tok.User == null)
    {
        //I'm there, but I 100% of sure thata this relation exists
        throw new Exception();
    }
}
Jacek
  • 11,661
  • 23
  • 69
  • 123

1 Answers1

1

The entity framework doesn't automatically load all the related objects out of the database - this could be very expensive if there were many tables with lots of relations. You either need to tell EF to load the associated User in your query (this is called Eager Loading), or you need to enable Lazy Loading so that EF will load it when it is first accessed. (See the MSDN article Loading Related Entities for more details.

Here's an example of Eager Loading (not thoroughly tested, since I don't have your model):

using (var db = new AccountDbContext())
{
    Token tok = db.Tokens.Include(n => n.User)
       .FirstOrDefault(p => tokenValue == p.Value) == 0);
}
BJ Myers
  • 6,617
  • 6
  • 34
  • 50