Entity Framework 未链接 Table

Entity Framework Does Not Get Linked Table

我只有两个 类(也是表格 - 使用代码优先的 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);
    }
}

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

您需要显式加载相关实体。这是通过 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

您应该为此使用预加载,请阅读有关预加载的更多信息 LINK。预加载是使用 Include() 方法

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

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