在EF 5,MVC 4无法检索导航性能数据 [英] can not retrieve data of navigation properties in EF 5, MVC 4
本文介绍了在EF 5,MVC 4无法检索导航性能数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下PersonelInCourse实体:
I have the following PersonelInCourse entity:
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; }
}
我插入这样的数据,它有没有问题:
I insert data like this and it has no problem:
...
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();
}
...
我尝试的地方像下面这样检索该信息。但是,这会导致一个例外,我发现所有的导航属性都为空,所以异常抛出:
I try to retrieve this info somewhere like the following. However, this causes an exception and I found out that all of navigation properties are null, so the exception throws:
@{
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++;
}
我如何能实现我想要什么?哪里是我的错?
How can I achieve what I want? Where is my mistake?
推荐答案
找到了! (根据@Liel的意见):
Found it! (based on comments of @Liel):
var psic = new jqPersonnelTraining.Models.PtDbContext().PersonnelInCourses
.Include("Personnel").Include("Personnel.Post").Where(p => p.CourseID == Model.ID);
亲爱Liel,必须添加 .INCLUDE()
在。凡()
...非常感谢为你的提示。
dear Liel, you must add .Include()
before .Where()
... Thanks a lot for your tips.
这篇关于在EF 5,MVC 4无法检索导航性能数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文