筛选器导航属性实体框架,返回 NULL

本文关键字:返回 NULL 框架 实体 导航 属性 筛选 | 更新日期: 2023-09-27 18:36:36

我正在尝试使用导航属性,但是当我使用它时,我收到错误

值不能为空。

这是可以理解的,因为 People 集合是 NULL,但为什么它是 NULL?

我真正想做的是通过请求者 ID 选择请求者的名称(最后一个代码片段的最后一行)

public abstract class Person
{
    [Key]     
    public int PersonID { get; set; }         
    public string FirstName { get; set; }      
} 
public class Employee : Person
{
    public string Department { get; set; }
}
public class FrDetail
{
    [Key]
    public int FrID { get; set; }      
    public int RequestorPersonID { get; set; }
    virtual public IList<Person> People { get; set; }
}
public class EFDbContext : DbContext
{      
       public DbSet<Person> People { get; set; }
       public DbSet<Employee> Employees { get; set; }
       public DbSet<FrDetail> FrDetails { get; set; }    
} 
public ViewResult List()
{
    EFDbContext context = new EFDbContext();
    IQueryable<FrDetail> frDetails = context.FrDetails.Include(x => x.People);
    return View(frDetails);
}
//The view
@model IQueryable<FrDetail>   
@foreach (var p in Model)
    Html.RenderPartial("FunctionRequestSummary", p);
}
//Partial View FunctionRequestSummary
@model FrDetail
@Model.People.Count()//IT'S ALWAYS ZERO
//@Model.People//NULL
@Model.People.Where(x=>x.PersonID==Model.RequestorPersonID).FirstOrDefault().FirstName

问题出在最后一行,其中计数始终为 0。我试过切换

ProxyCreationEnabled = false; 和 LazyLoadEnabled = false;

这也无济于事。我错过了什么吗?

筛选器导航属性实体框架,返回 NULL

这就是你要做的吗?

public abstract class Person
{
    [Key]     
    public int PersonID { get; set; }         
    public string FirstName { get; set; }      
} 
public class Employee : Person
{
    public string Department { get; set; }
}
public class FrDetail
{
    [Key]
    public int FrID { get; set; }      
    public virtual Person RequestorPerson { get; set; }
}
public class EFDbContext : DbContext
{      
       public DbSet<Person> People { get; set; }
       public DbSet<Employee> Employees { get; set; }
       public DbSet<FrDetail> FrDetails { get; set; }    
} 
public ViewResult List()
{
    EFDbContext context = new EFDbContext();
    IQueryable<FrDetail> frDetails = context.FrDetails;
    return View(frDetails);
}
//The view
@model IQueryable<FrDetail>   
@foreach (var p in Model)
{
    Html.RenderPartial("FunctionRequestSummary", p);
}
//Partial View FunctionRequestSummary
@model FrDetail
@Model.RequestorPerson.FirstName