Search code examples
entity-frameworklinked-tables

Entity Framework Does Not Get Linked Table


I have simply two classes (also tables - using code-first mvc5) When I try to get user, user's company doesnt come with EF6. Why is that?

Model:

 public class TblUser
{
    public int Id { get; set; }
    public string UserName { get; set; }
    public bool Gender { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public string Password { get; set; }
    public string Email { get; set; }

    public TblCompany TblCompany { get; set; }
}

  public class TblCompany
{
    public int Id { get; set; }
    public string CompanyName { get; set; }
    public string Email { get; set; }

    public List<TblUser> TblUsers { get; set; }
}

Context:

 public class DBContext : DbContext
{
    public DbSet<TblCompany> TblCompanies { get; set; }
    public DbSet<TblUser> TblUsers { get; set; }
}

Service:

      private DBContext db = new DBContext();
      public TblUser GetUserById(int id, bool showHidden = false)
    {

        return db.TblUsers.FirstOrDefault(x => x.Id == id && (!x.isDeleted || showHidden));
    }

Action:

 public class SupplierHomeController : Controller
{
    // GET: Supplier/SupplierHome
    public ActionResult Index()
    {
        UserService _srvUser = new UserService();

        //User info will be come from Session in the future
        //The User whose id is 1 is only for testing.
        TblUser u = _srvUser.GetUserById(1);

        //After that line, users's company is null! :( 
        //However there is a company linked to the user.

        SupplierDashboardViewModel model = new SupplierDashboardViewModel();
        model.TblUser = u;
        return View(model);
    }
}

When I try to get User from database, company info is getting null only. I am so confused.


Solution

  • You need to explicitly load the related entities. This is done with the Include() method:

    public TblUser GetUserById(int id, bool showHidden = false)
    {
        return db.TblUsers
            .Include(u => u.TblCompany)
            .FirstOrDefault(x => x.Id == id && (!x.isDeleted || showHidden));
    }
    

    More info here.