我有以下PersonelInCourse实体:不能在EF 5检索导航属性的数据,MVC 4
public partial class PersonnelInCourse
{
public int ID { get; set; }
public string PersonnelID { get; set; }
public string CourseID { get; set; }
public int HoursInCourse { get; set; }
public byte IsApproved { get; set; }
public byte IsPassed { get; set; }
public Nullable<int> RewardDetailID { get; set; }
public string RejectReason { get; set; }
public string FailReason { get; set; }
public virtual Course Course { get; set; }
public virtual RewardDetail RewardDetail { get; set; }
public virtual Personnel Personnel { get; set; }
}
我插入这样的数据,它有没有问题:
...
PersonnelInCourse p = new PersonnelInCourse();
p.CourseID = id;
p.PersonnelID = User.Identity.Name;
p.HoursInCourse = 0;
p.IsApproved = 0;
p.IsPassed = 0;
db.PersonnelInCourses.Add(p);
try
{
db.SaveChanges();
}
...
我尝试检索这个信息像下面的地方。然而,这会导致一个例外,我发现所有的导航属性为null,所以异常抛出:
@{
var psic = new Models.PtDbContext().PersonnelInCourses.Where(p => p.CourseID == Model.ID);
var c = new Models.PtDbContext().Courses.Find(Model.ID);
int i = 1;
} // these all are ok.
...
@foreach (var p in psic)
{
<tr style="border-bottom: 1px dotted black;">
<td>@i.ToString()</td>
<td>@string.Concat(p.Personnel.FirstName, " ", p.Personnel.LastName)</td>
//the exception throws from here, because the navigation property Personnel is null, and all other navPrs also are null.
<td>@p.Personnel.Post.PostName</td>
<td>@p.PersonnelID</td>
</tr>
i++;
}
我如何能实现我想要什么?我的错误在哪里?
将'.Load()'添加到您的查询中,以显式加载导航属性。 – Liel
其中模型定义在顶部像'@model namespance.Models.Navigation' – Sender
我已禁用延迟加载,我也在其他地方使用这种方法,我在那里没有问题。 – AminSaghi