S
S
stcmd042362016-06-17 14:22:33
Entity Framework
stcmd04236, 2016-06-17 14:22:33

Not loading property value in EF6. What is the problem?

Hello. Not long ago I started learning EF6. Here is an example:
DB Model.

public class User
  {
    public int Id {get;set;}

    public string FirstName {get;set;}

    public string SecondName {get;set;}

    public DateTime DateOfBirth {get;set;}

    public string Email {get;set;}

    public string Password {get;set;}

    public Token Token { get; set; }
  }

  public class Token
  {
    public int Id { get; set; }

    public string UUID { get; set; }

    public bool Status { get; set; }
  }

  public class DTBS : DbContext
  {
    public DTBS() : base("DBUsers")
    {
      base.Database.CreateIfNotExists();
    }


    public DbSet<User> Users { get; set; }

    public DbSet<Token> Tokens { get; set; }
  }

And this is the sample:
static void Main ( string[] args )
        {
      var db = new DTBS();
      
      var user = db.Users.FirstOrDefault();

      Console.Write(user.FirstName);
      Console.ReadLine();
        }

And here is the result
184edb05f3d140d89e47f800b7546e16.jpg
. Here the value of token is null. How to make related data or specific data automatically loaded.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Peter, 2016-06-17
@stcmd04236

db.Users.Include(u => u.Token).FirstOrDefault();

S
Sanostee, 2016-06-17
@andrewpianykh

Correct the model:

public class User
{
  public int Id {get;set;}

  public string FirstName {get;set;}

  public string SecondName {get;set;}

  public DateTime DateOfBirth {get;set;}

  public string Email {get;set;}

  public string Password {get;set;}

  public virtual Token Token { get; set; }
  
  public int TokenId { get; set; }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question