C# 为什么导航属性返回为空?
我在类中有导航属性。它在数据库中有关联,但不返回类型为Info导航属性的员工的数据C# 为什么导航属性返回为空?,c#,entity-framework,model-view-controller,entity-framework-6,navigational-properties,C#,Entity Framework,Model View Controller,Entity Framework 6,Navigational Properties,我在类中有导航属性。它在数据库中有关联,但不返回类型为Info导航属性的员工的数据 public class Visa { public int VisaID { get; set; } public string VisaName { get; set; } public Info EmployeeInfo { get; set; } public List<Info> Employees { get; se
public class Visa
{
public int VisaID { get; set; }
public string VisaName { get; set; }
public Info EmployeeInfo { get; set; }
public List<Info> Employees { 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>
}
更新:
这也不管用
public ActionResult VEmployees()
{
InfoDBContext InfoContext = new InfoDBContext();
//int EmployeeID = InfoContext.Infoes.ToList().Where(emp => emp.ID == 1).FirstOrDefault().ID;
object o = InfoContext.Visas.Include(e => e.Employees).Where(v => v.VisaName=="Hunain").FirstOrDefault().Employees;
return View(o);
}
为两个实体返回空这可能是因为未从数据库加载员工
public class Info
{
public int ID { get; set; }
public string Name { get; set; }
public string FatherName { get; set; }
}
在将数据传递给视图之前,可以尝试使用急切地加载。或为特定入境(visa)明确加载员工的。如果这不起作用,那么您可能已经破坏了模型中的关系。尝试在InfoDBContext
类中的OnModelCreating
方法中重新配置模型
检查本文:Info
您的Visa
模型类中的导航属性配置不正确。您引用了单个信息
和列表
,这没有意义。它应该是Info
或List
。但根据您的模型类结构,它似乎应该是列表
,如下所示:
public class Visa
{
public int VisaID { get; set; }
public string VisaName { get; set; }
public List<Info> Employees { get; set; }
}
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);
}
现在一切都好了 嗨,谢谢,等等。。。让我检查一下,然后再打给你。试试InfoContext.Visas.Include(=>u>.Employees)。Where(…).FirstOrDefault()。Employees
@Mika Kaskun:请检查更新的问题。根据您的建议,我已尝试但未工作。返回两个实体的空值try ToList()var employees=InfoContext.visa.Include(=>.employees).Where(…).FirstOrDefault().employees.ToList()
为什么没有意义EmployeeInfo
很可能是适用于其他员工的签证的所有者(或申请人,或其他任何人)。我想最好先问一下。@是的!可以!然后,您必须正确配置关系!应仔细映射这些混合关联。请显示您的EF映射。
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);
}