在EF 5,MVC 4不能检索导航属性的数据(can not retrieve data of na

2019-10-18 05:09发布

我有以下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();
}
...

我试着地方,比如下面的检索此信息。 然而,这会导致一个例外,我发现所有的导航属性为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++;
}

我如何能实现我想要什么? 哪里是我的错?

Answer 1:

您应该添加Include()导航性能的显负荷。

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

这将加载PersonnelInCourses及其Personnel在一个查询。

如果你需要加载一些更多的属性,只需链更加.Include("")的条款。



Answer 2:

尽量保持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++;
    }
}


Answer 3:

找到了! (基于@Liel的意见):

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

亲爱Liel,你必须添加.Include()之前.Where()为你的秘诀......非常感谢。



文章来源: can not retrieve data of navigation properties in EF 5, MVC 4