实体框架未获取链接表

时间:2017-03-14 11:04:17

标签: entity-framework linked-tables

我只有两个类(也是表 - 使用代码优先mvc5) 当我试图获得用户时,用户的公司不会使用EF6。 那是为什么?

型号:

 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; }
}

上下文:

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

服务:

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

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

动作:

 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);
    }
}

当我尝试从数据库中获取用户时,公司信息仅为空。我很困惑。

2 个答案:

答案 0 :(得分:0)

您需要显式加载相关实体。这是通过Include()方法完成的:

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

更多信息here

答案 1 :(得分:0)

您应该使用Eager加载,请在此LINK上阅读有关Eager-Loading的更多内容。使用Include()方法实现预先加载

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

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