我在课堂上有导航属性。它在数据库中具有关联,但不会从导航类型为 Info 的 Employees 返回数据。
text
在数据库中,信息类与Visa类之间也有一对多的关系。
NaiveBayes.train
视图中:
public class Visa
{
public int VisaID { get; set; }
public string VisaName { get; set; }
public Info EmployeeInfo { get; set; }
public List<Info> Employees { get; set; }
}
项目。员工为空。为什么?甚至表中也有数据。
更新:
此外,这不起作用。因此,总体而言,无论出于何种原因,员工都将空着返回。
public class Info
{
public int ID { get; set; }
public string Name { get; set; }
public string FatherName { get; set; }
}
更新:
这也不起作用。
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.VisaName)
</td>
@foreach (var employee in item.Employees)
{
<td>@Html.DisplayFor(empItem => employee.Name) </td>
<td>@Html.DisplayFor(empItem => employee.FatherName)</td>
}
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.VisaID }) |
@Html.ActionLink("Details", "Details", new { id=item.VisaID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.VisaID })
</td>
</tr>
}
两个实体都返回空
答案 0 :(得分:1)
这可能是因为未从数据库中加载Employees
。
在将数据传递到视图之前,您可以尝试使用快速加载。或显式加载 Employees
中的特定条目(签证)。如果这不起作用,则可能是您的模型中的关系破裂了。尝试在OnModelCreating
类内的InfoDBContext
方法中重新配置模型。
查看本文:https://docs.microsoft.com/en-us/ef/ef6/querying/related-data
答案 1 :(得分:1)
Info
模型类中的 Visa
导航属性未正确配置。您同时引用了单个Info
和List<Info>
,但这没有意义。它应该是Info
或List<Info>
。但是根据您的模型类结构,似乎应该List<Info>
如下:
public class Visa
{
public int VisaID { get; set; }
public string VisaName { get; set; }
public List<Info> Employees { get; set; }
}
然后按如下所示编写您的VEmployees
方法:
public ActionResult VEmployees()
{
InfoDBContext infoContext = new InfoDBContext();
List<Visa> vEmployees = infoContext.Visas.Include(e => e.Employees).Where(v => v.VisaName == "Hunain").ToList();
return View(vEmployees);
}
现在一切正常!