我只有两个类(也是表 - 使用代码优先的 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));
}
更多信息在这里。
您应该为此使用渴望加载,请在此链接上阅读有关渴望加载的更多信息。使用Include()
方法实现快速加载
public TblUser GetUserById(int id, bool showHidden = false)
{
return db.TblUsers.Include(s => s.TblCompany).FirstOrDefault(x => x.Id == id && (!x.isDeleted || showHidden));
}