4

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.

2 Answers2

4

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.

DavidG
  • 113,891
  • 12
  • 217
  • 223
0

You should use Eager loading for that please read about Eager-Loading more on this LINK.Eager loading is achieved using the Include() method

  public TblUser GetUserById(int id, bool showHidden = false)
  {

    return db.TblUsers.Include(s => s.TblCompany).FirstOrDefault(x => x.Id == id && (!x.isDeleted || showHidden));
  }
Curiousdev
  • 5,668
  • 3
  • 24
  • 38