1

我有以下 PersonelInCourse 实体:

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();
}
...

我尝试在如下所示的地方检索此信息。但是,这会导致异常,我发现所有导航属性都是空的,所以异常抛出:

@{    
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++;
}

我怎样才能达到我想要的?我的错误在哪里?

4

3 回答 3

2

您应该添加Include()导航属性的显式加载。

var psic = new Models.PtDbContext().PersonnelInCourses..Include("Personnel").Where(p => p.CourseID == Model.ID);

这将在一个查询中加载PersonnelInCourses它们。Personnel

如果您需要加载更多属性,只需链接更多.Include("")子句。

于 2013-05-30T06:15:57.103 回答
1

尝试保持PtDbContext活动状态,直到您完成处理来自它的数据并显式测试导航属性:

@using (var context = new Models.PtDbContext()){    
    var psic = context.PersonnelInCourses.Where(p => p.CourseID == Model.ID);
    var c = context.Courses.Find(Model.ID);
    int i = 1;
<table>
    @foreach (var p in psic)
    {
    <tr style="border-bottom: 1px dotted black;">
        <td>@i.ToString()</td>
        @if (p.Personnel == null)
        {
        <td><b>not found</b></td> 
        <td><b>not found</b></td>
        }
        else
        {
        <td>@string.Concat(p.Personnel.FirstName, " ", p.Personnel.LastName)</td> 
        <td>@p.Personnel.Post.PostName</td>
        }
        <td>@p.PersonnelID</td>
    </tr>
</table>
        @i++;
    }
}
于 2013-05-30T09:42:15.453 回答
1

找到了!(基于@Liel 的评论):

var psic = new jqPersonnelTraining.Models.PtDbContext().PersonnelInCourses
    .Include("Personnel").Include("Personnel.Post").Where(p => p.CourseID == Model.ID);

亲爱的 Liel,您必须先添加.Include()....Where()非常感谢您的提示。

于 2013-05-30T10:50:35.037 回答